1

我必须在不使用任何 xib 或情节提要的情况下执行此 UIview 子类,它需要是 1 个文件,因此我需要在代码中设置此 tableview 并避免子类化 UITableViewCell。

我正在尝试将图像视图设置为 V:|-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 )>

4

1 回答 1

1

必须translatesAutoresizingMaskIntoConstraints=NO为使用自动布局约束的任何视图进行设置。如果您不这样做,除了您手动添加的任何约束之外,与 匹配的自动布局约束autoResizingMask将自动添加到视图中。这几乎总是会导致一个过度约束的视图,其中一个或多个约束必须被打破才能布局视图。

于 2014-10-24T15:19:35.467 回答