我正在向UICollectionViewCell添加子视图。我以编程方式添加约束以使其填充单元格,但宽度不会填充单元格。
当我在视图调试器中查看它时,它表示位置不明确。这是怎么回事,因为我指的是所有4个方面都固定在superview上?
这是调试器中的视图。内部白色视图应符合父项宽度(蓝色边框):
检查父视图上的约束会显示"位置不明确"警告:
我使用的代码如下:
[self.contentView addSubview:calloutView];
calloutView.translatesAutoresizingMaskIntoConstraints = NO;
self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[calloutView]-0-|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(calloutView) ]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[calloutView]-0-|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(calloutView) ]];
答案 0 :(得分:1)
问题似乎与使用contentView有关,你必须使用单元格本身来实现你想要的,这是代码和工作原理,查看下面的图片
#import "CollectionViewCell.h"
@interface CollectionViewCell()
@property UIView * testView;
@end
@implementation CollectionViewCell
@synthesize testView;
-(void)awakeFromNib
{
[super awakeFromNib];
testView = [[UIView alloc]initWithFrame:CGRectZero];
testView.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:testView];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-2-[testView]-2-|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(testView) ]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-2-[testView]-2-|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(testView) ]];
self.testView.layer.borderWidth = 2;
self.testView.layer.borderColor = [UIColor blueColor].CGColor;
}
@end
我希望这能帮到你,最好的问候