使用边距检索UITableViewCell的框架

时间:2015-01-11 11:08:20

标签: ios uitableview

我正在尝试创建一个可编辑的UITableViewCell,它可以正常工作,但我错过了一个边距:

enter image description here

文字直接对齐左边,没有边距。所以我认为cell.frame部分有点不对。

但我不知道还有什么用,我试过cell.contentView.frame,没有任何作用:

UITextField *textField = [[UITextField alloc] initWithFrame:cell.frame];

textField.placeholder     = @"What's your email address?";
textField.clearButtonMode = UITextFieldViewModeNever;
textField.textAlignment   = NSTextAlignmentLeft;

[cell.contentView addSubview: textField];

return cell;

P.S我可能稍后添加一个图标,我也不能使用静态保证金,必须以某种方式计算

2 个答案:

答案 0 :(得分:1)

这应该向您展示如何以快速和肮脏的方式实现这一目标。只需删除它就可以代替现有的相同命名方法来查看最新情况,然后重构它

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"myCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];

    if (cell == nil) {

        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectZero];

        textField.placeholder     = @"What's your email address?";
        textField.clearButtonMode = UITextFieldViewModeNever;
        textField.textAlignment   = NSTextAlignmentLeft;
        textField.text = @"hi";

        if ([textField respondsToSelector:@selector(setTranslatesAutoresizingMaskIntoConstraints:)]) {
            [textField setTranslatesAutoresizingMaskIntoConstraints: NO];
        }

        [cell.contentView addSubview: textField];

        NSDictionary * viewsDictionary = NSDictionaryOfVariableBindings(textField);

        [cell addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[textField]-10-|" options:0 metrics: 0 views:viewsDictionary]];

        [cell addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(>=1)-[textField(==20)]-(>=1)-|" options:0 metrics: 0 views:viewsDictionary]];

        [cell addConstraint:
         [NSLayoutConstraint constraintWithItem:textField
                                  attribute:NSLayoutAttributeCenterY
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:cell
                                  attribute:NSLayoutAttributeCenterY
                                 multiplier:1
                                   constant:0]];

        textField.backgroundColor = [UIColor grayColor];

    }

    return cell;

}

答案 1 :(得分:0)

您可以计算textField的保证金:

CGFloat hPadding = 10.0;
CGRect frame = CGRectMake(hPadding, 0.0, 
                          NSWidth(cell.frame) - hPadding * 2.0, NSHeight(cell.frame))

UITextField *textField = [[UITextField alloc] initWithFrame:frame];