使用NSLayoutConstraint constraintWithVisualFormat在基本UITableVewCell中设置图像视图

时间:2014-10-23 14:02:41

标签: ios iphone uitableview nslayoutconstraint visual-format-language

我必须使用任何xib或storyboard来执行此UIview子类,它需要是1个文件,因此我需要在代码中设置此tableview并避免继承UITableViewCell。

我正在尝试将图像视图设置为 五:| -5- [imageview的] -5- |和H:[iamgeview(width = height)] - 5- |在单元格的contentView中。

我得到的是我所有增加的约束都被打破了,而单元格不在我想要的位置。

基本单元格是基本样式单元格。我想要做的就是在视图的末尾添加一个图像视图,此刻正在变成一场噩梦。

我在代码中按如下方式设置图像视图。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

if (!cell)
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
POI *poi = [self.results objectAtIndex:indexPath.row];
NSString *text = poi.name;

cell.textLabel.text = text;

UIImageView *image = [[UIImageView alloc] init];
image.image = [UIImage imageWithColor:[UIColor blueColor]];
[cell.contentView addSubview:image];
NSDictionary* viewDic = @{@"image":image};
cell.contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
[cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[image]"
                                                                         options:0
                                                                         metrics:nil
                                                                           views:viewDic]];

[cell.contentView addConstraints: [NSLayoutConstraint constraintsWithVisualFormat:@"H:[image(w)]-5-|"
                                                                          options:0
                                                                          metrics:@{@"w":cell.contentView.frame.size.heigh}
                                                                            views:viewDic]];

return cell;

}

当单元格加载时,我收到此错误:

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x7fb7b636aaa0 H:[img(44)]   (Names: img:0x7fb7b6368fc0 )> 

<NSLayoutConstraint:0x7fb7b6369380 V:[img(44)] (Names: img:0x7fb7b6368fc0 )>

<NSLayoutConstraint:0x7fb7b636aaf0 H:[img]-(5)-| (Names: Contentview:0x7fb7b6372a30, img:0x7fb7b6368fc0, '|':Contentview:0x7fb7b6372a30 )>

<NSLayoutConstraint:0x7fb7b63697e0 V:|-(5)-[img] (Names: img:0x7fb7b6368fc0, Contentview:0x7fb7b6372a30, '|':Contentview:0x7fb7b6372a30 )>

1 个答案:

答案 0 :(得分:1)

必须为您使用自动布局限制的任何视图设置translatesAutoresizingMaskIntoConstraints=NO。如果您不这样做,匹配autoResizingMask的自动布局约束将自动添加到视图以及手动添加的任何约束。这几乎总是会导致过度约束的视图,其中必须打破一个或多个约束以布局视图。