我的 UITableViewCell 设置按钮 [英] my UITableViewCell setting button

查看:23
本文介绍了我的 UITableViewCell 设置按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在向 UITableViewCell 添加按钮时遇到问题,单元格有两个 UILabel 和两个 UIImageView,有时是 UIImageView 将包含一个图像,有时包含一个按钮:

I'm having trouble adding button to my UITableViewCell, the cell has two UILabels and two UIImageViews, sometimes the UIImageView will contain an image and sometimes a button:

在我的 UITableViewCell 子类中,我有:

In my UITableViewCell subclass I have:

- (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 中的一个只是图像时没问题,但是当我添加 UIButton(图像)作为子视图时它会崩溃.

When one of the UIImageViews is just an image no problem, but it crashes when I add a UIButton (imaged) as a subview.

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];

添加按钮作为图像视图的子视图崩溃:

Adding a button as a subview of the image view crashes:

 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 默认没有,按钮没有它就不能工作!

Because the UIImageView has NO as default and the button doesn't work without it!

推荐答案

如果您阅读了崩溃错误,就很容易看出问题出在哪里.您尚未初始化按钮.

If you read the crash error it is quite easy to see where your issue is. You have not initialized your button.

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0,0,0,0)];

或者你可以使用 initWithCoder.

or you can use initWithCoder.

希望能帮到你

山姆

这篇关于我的 UITableViewCell 设置按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆