我无法将图像居中放在桌面行上。我想确保将图像集中在所有iOS设备上。所以我制作了一个自定义单元格,它有一个基本的图像视图。
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
float imgWidth = 250;
float imgHeight = 250;
self.showImage = [[UIImageView alloc]initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width/2)-(imgWidth/2),0,imgWidth,imgHeight)];
[self.contentView addSubview:self.showImage];
}
return self;
}
因此,在索引路径中的行的单元格中,方法包含以下约束。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
SponsorCell * cell = [tableView dequeueReusableCellWithIdentifier:@"sponsorCell"];
if (!cell) {
cell = [[SponsorCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"sponsorCell"];
}
///....Arithmetic for processing image and other data...
image = [UIImage imageWithContentsOfFile:pdfPath];
[cell.contentView addConstraint:[NSLayoutConstraint constraintWithItem:cell attribute:NSLayoutAttributeCenterX relatedBy:0 toItem:cell.showImage attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
[cell.showImage setImage:image];
cell.showImage.accessibilityLabel =accessibilityLabel;
}
当我执行代码时,
我得到以下异常:
7:26:57.789 Demo[56438:21023305] Exception: Unable to install constraint on view. Does the constraint reference something from outside the subtree of the view? That's illegal
从其他堆栈流动帖子中,我理解我需要将约束添加到更高级别,例如tableview。我的理解是否正确?我可以在xib中添加很好的约束,我只是以编程方式进行粗略的时间。有人可以解释我的方法/思考有什么问题吗?真的很想从中吸取教训。希望我很清楚。一个例子将非常感激。
答案 0 :(得分:0)
customImageView = [[UIImageView alloc] init];
customImageView.translatesAutoresizingMaskIntoConstraints = NO;
[cell.contentView addSubview:customImageView];
image = [UIImage imageWithContentsOfFile:pdfPath];
[customImageView setImage:image];
[cell.contentView addConstraint:[NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeCenterX relatedBy:0 toItem:customImageView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
[cell.contentView addConstraint:[NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeCenterY relatedBy:0 toItem:customImageView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
工作得很漂亮。请注意,请确保autoResizingMaskingIntoConstraints设置为NO;