我在向我UITableViewCell
的 中添加按钮时遇到问题,单元格有两个UILabel
s 和两个UIImageView
s,有时UIImageView
会包含一个图像,有时会包含一个按钮:
在我的UITableViewCell
子类中,我有:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if ( self ) {
// Initialization code
firstLock = [[UILabel alloc]init];
[firstLock setBackgroundColor:[UIColor clearColor]];
firstLock.textAlignment = UITextAlignmentLeft;
firstLock.font = [UIFont fontWithName:@"Arial-BoldMT" size:17];
secondLock= [[UILabel alloc]init];
[secondLock setBackgroundColor:[UIColor clearColor]];
secondLock.textAlignment = UITextAlignmentRight;
secondLock.font = [UIFont fontWithName:@"Arial-BoldMT" size:17];
firstLockImage = [[UIImageView alloc]init];
secondLockImage = [[UIImageView alloc] init];
[self.contentView addSubview:firstLock];
[self.contentView addSubview:secondLock];
[self.contentView addSubview:firstLockImage];
[self.contentView addSubview:secondLockImage];
}
return self;
}
当其中一个UIImageView
s 只是一个图像时没问题,但是当我添加一个UIButton
(imaged) 作为子视图时它会崩溃。
在UITableViewDataSource
实施中:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIImage *btnImage = [UIImage imageNamed:@"bike_ok.png"];
UIButton *button =[UIButton alloc];
[button setImage:btnImage forState:UIControlStateNormal];
[cell.secondLockImage addSubview:button];
添加按钮作为图像视图的子视图崩溃:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Requesting the window of a view (<UIButton: 0x7bac7d0; frame = (0 0; 0 0); transform = [0, 0, 0, 0, 0, 0]; alpha = 0; opaque = NO; userInteractionEnabled = NO; layer = (null)>) with a nil layer. This view probably hasn't received initWithFrame: or initWithCoder:.'
*** First throw call stack:
我错过了什么?
谢谢!
只需添加!这条线很重要
[firstLockImage setUserInteractionEnabled:YES];
[secondLockImage setUserInteractionEnabled:YES];
因为 UIImageView 默认设置为 NO 并且没有它按钮将无法工作!