2 daffodilgirl DaffodilGirl 于 2013.01.07 13:10 提问

怎么给编程添加的控制保存关联

在我的view中有3个Button,然后把按钮添加到数组中,这样就可以获取:

for (i = 0; i < 3; i++)
{
  UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
  [view addSubview:button];
  [_buttons addObject:button];
}

如果在数组中关联按钮,修改按钮图片,屏幕上的按钮背景并没有改变:

UIButton* button = [_buttons objectAtIndex: 0];
[button setImage:thumb forState:UIControlStateNormal];

后来我在subview中用loop循环实现了修改按钮图片,不知道有没有更好的方法?

for (UIView* subView in ((UIView*)[self.view.subviews objectAtIndex:0]).subviews){
    if ([subView isKindOfClass:[UIButton class]]){
        UIButton *button = (UIButton*)subView;
        if (button.tag == self.selected){
            [button setImage:thumb forState:UIControlStateNormal];
        }
    }
}

3个回答

redCoral_
redCoral_   2013.01.07 14:13
已采纳

常见的原因是你的数组没有初始化。Objective C这种情况不会报出异常,相反,系统会无视添加的调用。当获取items结束时会返回空值。

添加这行到viewDidLoad方法中:

_buttons = [NSMutableArray array];

应该就能解决了

DaffodilGirl
DaffodilGirl 谢谢~
5 年多之前 回复
g989_1314125
g989_1314125   2013.01.07 13:54

给Button添加一个tag。然后通过tag获得Button:

for (i = 0; i < 3; i++)
{
  UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
  button.tag = i+1;
  [view addSubview:button];
  [_buttons addObject:button];
}

然后如下访问:

UIButton *button1 = (UIButton *)[self.view viewWithTag:1];
UIButton *button2 = (UIButton *)[self.view viewWithTag:2];
UIButton *button3 = (UIButton *)[self.view viewWithTag:3]

;

lianlianbushell
lianlianbushell   2013.01.07 14:09
  -(void)clickEvent:(id)sender
  {
       [sender setImage:thumb forState:UIControlStateNormal];
  }

可能用click事件也能解决

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!