我的CustomTableCell上有四个按钮。
按钮名称为button1
,button2
,button3
,button4
。 (如.h文件中所声明的那样)
@property (weak, nonatomic) IBOutlet UIButton *button1;
@property (weak, nonatomic) IBOutlet UIButton *button2;
@property (weak, nonatomic) IBOutlet UIButton *button3;
@property (weak, nonatomic) IBOutlet UIButton *button4;
以下代码工作正常,我通过重复代码生成这样的4个按钮。
CustomTableViewCell *cell = [self.tableVIew dequeueReusableCellWithIdentifier:@"CustomCell"];
[cell.button1.titleLabel setFont:[UIFont systemFontOfSize:13]];
cell.button1.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.button1.titleLabel.textAlignment = NSTextAlignmentLeft;
cell.button1.titleLabel.numberOfLines = 0;
[cell.button1 setTitle:@"button1 title" forState:UIControlStateNormal];
[cell.button1 setSelected:NO];
现在我使用了四个按钮,它们将有四个不同的名称(不是标题)。
_buttonTitle = [@[@"button1 title",
@"button2 title",
@"button3 title",
@"button4 title"] mutableCopy];
所以我想为什么不在这样的for循环中生成按钮。
for (int i = 0; i <= _buttonTitle.count ; i++) {
NSString *buttonNumber = [NSString stringWithFormat:@"%d", i+1];
NSString *buttonName = [@"button" stringByAppendingString:buttonNumber];
[cell.buttonName.titleLabel setFont:[UIFont systemFontOfSize:13]];
cell.buttonName.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.buttonName.titleLabel.textAlignment = NSTextAlignmentLeft;
cell.buttonName.titleLabel.numberOfLines = 0;
// NSLog(buttonName);
[cell.buttonName setTitle:_buttonTitle[i] forState:UIControlStateNormal];
[cell.buttonName setSelected:NO];
}
我收到以下错误:
"Property 'buttonName' not found on object of type 'CustomTableViewCell *'"
当然这是有道理的,因为cell.button1 != cell.buttonName
event buttonName
NSString
是button1
,其值为{{1}}。
所以我要问的问题的要点是,如果我知道.h文件中声明的按钮名称,我怎么能创建一个按钮?
答案 0 :(得分:2)
您是否想知道如何以编程方式创建按钮?如果是这样的话:
UIButton *btn = [[UIButton alloc] init];
[btn setTitle:@"YOUR TITLE" forState:UIControlStateNormal];
如果您要设置按钮的标题并且该标题存储在数组中,您可以执行以下操作:
UIButton *btn = [[UIButton alloc] init];
[btn setTitle:[NSString stringWithFormat:@"%@", [self.yourButtonTitleArray objectAtIndex:index]] forState:UIControlStateNormal];
答案 1 :(得分:0)
buttonName
不是一个按钮,而是一个字符串。
尝试为每个按钮设置tag
,例如带标签0的button1,带标签1的button2,依此类推。您可以在视图的界面(.xib文件)
然后将代码更新为以下内容,它应该可以工作:
for (int i = 0; i <= _buttonTitle.count ; i++) {
NSString *buttonNumber = [NSString stringWithFormat:@"%d", i+1];
//I removed this
//NSString *buttonName = [@"button" stringByAppendingString:buttonNumber];
//I added this
UIButton* currentButton = (UIButton*)[cell viewWithTag:i];
[currentButton.titleLabel setFont:[UIFont systemFontOfSize:13]];
currentButton.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
currentButton.titleLabel.textAlignment = NSTextAlignmentLeft;
currentButton.titleLabel.numberOfLines = 0;
// NSLog(buttonName);
[currentButton setTitle:_buttonTitle[i] forState:UIControlStateNormal];
[currentButton setSelected:NO];
}
答案 2 :(得分:0)
考虑到您要实现的目标,如果要验证按钮的数量,我建议使用运行时属性创建。有关详细信息,请参阅此Question。但是,如果您只在单元格中显示这四个按钮,请不要尝试任何花哨的东西。在第一种方法中使用静态属性声明是完全可以的。