所以我在UITableView中的CustomCell类中的UILabel下面有UIButtons。我得到了标签,但似乎无法显示按钮。我在自定义单元格中为所有3个UI元素设置了所有方向的约束。
我还记录了每个按钮的框架,它们似乎位于我单元格的框架内。
以下是我用来设置每个单元格的代码
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_questions count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CustomCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
cell.questionLabel.text = _questions[indexPath.row];
cell.questionLabel.numberOfLines = 0;
cell.disagreeButton.tag = indexPath.row;
cell.agreeButton.tag = indexPath.row + 60;
[cell.contentView addSubview:[cell.disagreeButton viewWithTag:indexPath.row]];
[cell.contentView addSubview:[cell.agreeButton viewWithTag:indexPath.row + 60]];
[cell.disagreeButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.agreeButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
NSLog(@"Button 1 Frame: %@\n", cell.disagreeButton);
NSLog(@"Button 2 Frame: %@\n", cell.agreeButton);
NSLog(@"Cell Frame: %@\n", cell);
return cell;
}
- (void)buttonClicked:(id)sender {
UIButton *senderButton = (UIButton *)sender;
if (senderButton.tag < 60) {
NSLog(@"Disagree Selected\n");
} else {
NSLog(@"Agree Selected\n");
}
}
我的CustomCell.h
#import "UIKit/UIKit.h"
@interface CustomCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel* questionLabel;
@property (weak, nonatomic) IBOutlet UIButton* disagreeButton;
@property (weak, nonatomic) IBOutlet UIButton* agreeButton;
@end
答案 0 :(得分:1)
[cell.contentView addSubview:[cell.disagreeButton viewWithTag:indexPath.row]];
[cell.contentView addSubview:[cell.agreeButton viewWithTag:indexPath.row + 60]];
[cell.disagreeButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.agreeButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
删除这些行并查看。当您将自定义类提供给单元格时,您不必再次进行子视图。
答案 1 :(得分:0)
如果您使用的是自定义类,则无需将按钮添加为子视图。但是如果你想使用标签添加按钮作为子视图,那么使用 -
[cell.contentView addSubview:[cell viewWithTag:indexPath.row]];
和
[cell.contentView addSubview:[cell viewWithTag:indexPath.row + 60]];
答案 2 :(得分:-1)
显示单元格的高度似乎很小,以显示按钮,因此按钮被切断。尝试也实现这个方法:
func tableView(_ tableView: UITableView,heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
return 300
}
尝试使用300作为细胞的高度。如果您可以看到按钮,则可以返回正确的单元格高度。