从UICollectionView宽度设置Ancor约束中的宽度

时间:2017-10-10 14:50:22

标签: ios objective-c autolayout constraints

我需要使用UICollectionView的锚约束来构建UIView。我插入的锚点都是正确的但是我对widthAncor有问题......我解释一下:

这是我的CollectionView

_monthCollection = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:monthCollectionLayout];
    [self addSubview:_monthCollection];

    [_monthCollection.topAnchor constraintEqualToAnchor:self.topAnchor constant:65].active = YES;
    [_monthCollection.leftAnchor constraintEqualToAnchor:self.leftAnchor constant:2].active = YES;
    [_monthCollection.rightAnchor constraintEqualToAnchor:self.rightAnchor constant:0].active = YES;
    [_monthCollection.bottomAnchor constraintEqualToAnchor:self.bottomAnchor constant:0].active = YES;

这是我添加的UIView

UIView *cursor = [[UIView alloc] init];
    cursor.backgroundColor = [UIColor colorWithHexString:@"#E66163" setAlpha:.4];
    cursor.layer.borderColor = [UIColor colorWithHexString:@"#E66163" setAlpha:1].CGColor;
    cursor.layer.borderWidth = 1;
    cursor.layer.cornerRadius = 15;
    cursor.translatesAutoresizingMaskIntoConstraints = NO;
    [_monthCollection addSubview:cursor];

    [cursor.topAnchor constraintEqualToAnchor:_monthCollection.topAnchor constant:0].active = YES;
    [cursor.leftAnchor constraintEqualToAnchor:_monthCollection.leftAnchor constant:0].active = YES;
    [cursor.widthAnchor constraintEqualToConstant:_monthCollection.frame.size.width].active = YES;
    [cursor.bottomAnchor constraintEqualToAnchor:_monthCollection.bottomAnchor constant:0].active = YES;

我需要我的UIVIEW的宽度等于_monthCollection.frame.size.width / 3

我试过各种各样的方式,但似乎是约束我什么都不关心......我无法得到任何结果......

所以我想知道......当我使用锚点约束时如何插入宽度?

1 个答案:

答案 0 :(得分:1)

您使用了错误的方法来创建约束。您希望将视图的宽度限制为集合的宽度,而不是将其设置为常量。我没有"说" ObjC,但我相信你可以轻松地将我的Swift代码重写为objC:

cursor.widthAnchor.constraint(equalTo: _monthCollection.widthAnchor, multiplier: 0.33).isActive = true