2017-03-17 77 views
0

我正在向UICollectionViewCell添加子视图。我正在编程添加约束来填充单元格,但宽度不填充单元格。子视图宽度不适合superview与自动布局

当我在视图调试器中查看它时,它表示位置不明确。这是怎么回事,因为我指定所有4面都固定在超视图上?

这就是调试器中的视图。内,白色视图应该适合父母宽度(蓝色边框):

enter image description here

检查在父视图的约束示出该与“位置模糊”警告:

enter image description here

我正在使用的代码如下:

[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

凡你使用这个代码? –

+0

UICollectionViewDelegate创建一个单元格,然后调用包含此代码的单元格设置方法 – zorro2b

+0

,但此代码位于您的单元格内或您的viewController中? –

回答

1

该问题似乎与使用内容查看,你必须使用电池本身达到你想要的东西,这是代码和工程,检查以下

#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 

enter image description here

图片我希望这可以帮助你,最好的问候

+0

谢谢你。你在使用contentView时重现了这个问题吗?我刚刚删除它,看到没有变化:( – zorro2b

+0

@ zorro2b我发布你的问题的答案,是的我重现你的问题,解决方案是这样的,使用单元格本身,而不是contentView添加您的代码创建的视图和设置你的约束,因为我的代码显示,它的工作原理!,最好的问候 –

+0

@ zorro2b我的答案终于帮助你? –