【问题标题】:Best route to fit a UITextField to UITableView cell将 UITextField 适合 UITableView 单元格的最佳途径
【发布时间】:2013-02-25 22:27:56
【问题描述】:

我想知道使 UITextField 适合 UITableView 单元格的最佳方法是什么。

我以前用过这个方法:

@implementation UITextField (custom)
- (CGRect)textRectForBounds:(CGRect)bounds {
    return CGRectMake(bounds.origin.x + 0, bounds.origin.y + 10,
                      bounds.size.width - 30, bounds.size.height - 16);
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
    return [self textRectForBounds:bounds];
}
@end

但这会导致一个问题:

Category is implementing a method which will also be implemented by its primary class

虽然我已经看到了隐藏这些警告的方法,但感觉这更像是一种 hack,而不是正确的方法。

使 UItextField 适合单元格的最佳方法是什么。这是我的领域:

// Username field
usernameField = [[UITextField alloc] initWithFrame:(CGRectMake(10, 0, 300, 43))];
usernameField.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

像这样输入到单元格中:

if (indexPath.row == 0) {
        [cell.contentView addSubview:usernameField];
    } 

图片:

【问题讨论】:

    标签: ios ios5 uitableview uitextfield


    【解决方案1】:

    我建议通过覆盖您的自定义 UITableViewCell 的 layoutSubviews 方法来做到这一点。 imo 那里简单得多。比如:

        - (void)layoutSubviews
        {
            [super layoutSubviews];
            float  w, h;
    
            w = (int)(self.frame.size.width - 30);          
                h = (int)(self.frame.size.height - 16);
    
            [self.detailTextLabel setFrame:CGRectMake(0, 10, w, h)];
        }
    

    这是自定义单元格初始化的片段

        @interface MyCustomCell: UITableViewCell {
    
        }
        @end
    
        @implementation MyCustomCell
    
    
        - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
        {
            if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
                }
                return self;
        }
    

    这是创建自定义单元格的片段:

        - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
            static NSString *CellIdentifier = @"Cell";
    
            MyCustomCell *cell = (MyCustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[[MyCustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
            }
    

    【讨论】:

    • 您能详细解释一下如何请吗?
    • 刚刚添加了有关 layoutSubviews 方法的详细信息。我假设您已经有一个自定义 UITableViewCell?
    • 这会影响所有子视图吗?我以编程方式设置所有子视图,这会影响所有子视图还是仅影响文本字段
    • 只是您明确设置的 uitableviewcell 中的子视图。在示例中,我只是设置了 UITableViewCell 的内置 detailTextLabel 框架。 [super layoutSubviews] 确保其他所有内容都像以前一样绘制
    • 只是为了确认这是一个 UIViewController 设置为 TableViewDelegate 并且所有更改都以编程方式进行,而不是 Interface Builder 和 Nibs
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 2011-02-02
    相关资源
    最近更新 更多