[英]Call methods on UIButton objects in NSMutableArray Objective-C
I have an array called buttons which consists of UIButton objects. 我有一个名为按钮的数组,其中包含UIButton对象。 I populate it as follows:
我将其填充如下:
for (int i=0; i<self.numButtons; i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Title" forState:UIControlStateNormal];
button.frame = CGRectMake(xCoord-40, y, 80, 20);
[button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[button setTag:i];
[self.buttons addObject:button];
[self.view addSubview:button];
y+= 45;
}
The action for these buttons is buttonAction. 这些按钮的动作是buttonAction。 This action is supposed to change the color of the selected button.
应该执行此操作来更改所选按钮的颜色。 Here is how I have it implemented:
这是我的实现方式:
-(void) buttonAction:(id)sender{
int num = (int)[sender tag];
[[self.buttons objectAtIndex:num] setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
NSLog(@"%@", [self.buttons objectAtIndex:buttonClicked].titleLabel.text);
}
The result is that there is no color change. 结果是没有颜色变化。 Even when I try to NSLog the title of the button it returns (null).
即使当我尝试NSLog按钮的标题时,它也会返回(空)。 So my question is how can I fix this but also how do I call methods on objects inside arrays?
所以我的问题是如何解决此问题,又如何在数组内部的对象上调用方法? Any help would be appreciated.
任何帮助,将不胜感激。 Thanks!
谢谢!
All evidence points to self.buttons
being nil
. 所有证据都表明
self.buttons
nil
。 Did you ever initialize it? 您曾经初始化过吗?
Somewhere you need a line like: 您需要在某处输入以下内容:
self.buttons = [NSMutableArray array];
Of course you could use the sender
parameter to your buttonAction:
method: 当然,您可以在
buttonAction:
方法中使用sender
参数:
- (void)buttonAction:(UIButton *)button {
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}
Note the change in the parameter. 注意参数的变化。
I like to do this. 我喜欢这样做。 Don't forget to use IBAction.
不要忘记使用IBAction。 It will help if you decide to use a nib or storyboard.
如果您决定使用笔尖或情节提要,这将有所帮助。
-(IBAction) buttonAction:(id)sender{
[((UIButton*)sender) setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]
NSLog(@"%@", ((UIButton*)sender).titleLabel.text)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.