2017-03-17 101 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我的答案終於幫助你? –