【问题标题】:Set width in Ancor Constraint from UICollectionView width从 UICollectionView 宽度设置 Ancor 约束中的宽度
【发布时间】:2017-10-10 14:50:22
【问题描述】:

我需要使用 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

我尝试了所有方法,但似乎约束我什么都不在乎..我无法得到任何结果...

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

【问题讨论】:

    标签: ios objective-c autolayout constraints


    【解决方案1】:

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

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

    【讨论】:

    • 现在宽度是正确的..我很容易误认为约束...你能告诉我其他约束是否也正确吗?
    • 不太确定您要达到的目标,但如果您的目标是拥有一个“光标”,它的高度与 collectionView 相同,宽度 = 1/3,并且定位到collectionView 的左侧,然后它们看起来是正确的
    • 那么现在我应该如何在 didSelectItemAtIndexPath 中为 leftAncor 设置动画?
    • 保留对设置光标位置的约束的引用,并对其进行操作——要么将其常量更改为将其移动到所需位置的偏移量,要么停用它并再次创建一个新的这会将其移动到正确的位置(例如,将左锚绑定到所选单元格的左锚)
    • 你给了我一个好主意,我从来没有尝试绑定一个单元格的静止...但是在 didSelectItemAtIndexPath 我如何找到下一个单元格的静止
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2018-02-25
    • 1970-01-01
    • 2019-04-19
    相关资源
    最近更新 更多