简体   繁体   中英

UITextField in custom UITableViewCell not visible

I am creating a custom UITableViewCell (programmatically, by subclassing) with one label and one text field.

This code

#import "TextCell.h"

@implementation TextCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        UITextField *subjectField = [[UITextField alloc] initWithFrame:CGRectMake(59, 11, 399, 21)];

        subjectField.font = [UIFont systemFontOfSize:17];
        subjectField.placeholder = @"(placeholder)";

        [self.contentView addSubview:subjectField];

        self.textField = subjectField;
    }
    return self;
}

results in invisible text field:

不可见字段的屏幕截图

But if I select this cell, the text field becomes visible:

在此处输入图片说明

If I implement

- (void)layoutSubviews
{
     self.textField.frame = CGRectMake(59, 11, 399, 21);

     /* thus text field init method becomes initWithFrame:CGRectZero;
}

the text field becomes visible, but the label goes away and the cell's width suddenly increases:

在此处输入图片说明

Please, point me in the right direction.

With your first attempt, the text field will be behind the label, and so not visible. I assuming that's the standard label from the cell that you are using? It doesn't get created until you access it, and by default it is the full width of the cell, so it covers your text field. Use your own custom label with a specific frame to avoid this.

In the second example, you've forgotten to call [super layoutSubviews] which is very important.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM