如何将宽度等同于NSLayoutConstraint的某些UIViews?
我如何可以钉住两个以上宽度的UIViews同样使用NSLayoutConstraints?
现在,我使用下面的代码,我不能钉住两个以上的UIViews:
for (int i = 0; i < column.count; i++) { NSString *horizontalFormat = @"H:|[view1][view2(==view1)]|"; NSDictionary *views; if (i < column.count - 1) { views = @{ @"view1": column[i], @"view2": column[i + 1] }; }else{ views = @{ @"view1": column[i - 1], @"view2": column[i] }; } NSArray * horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:horizontalFormat options:NSLayoutFormatAlignAllTop | NSLayoutFormatAlignAllBottom metrics:nil views:views]; [self.contentView addConstraints:horizontalConstraints]; }
有任何想法吗?
这是一个例子。 所有的视图都是在代码中生成的,所以只要将这个代码直接复制到一个UIViewController(例如到它的viewDidLoad
)并运行它:
UIView* v1 = [[UIView alloc] init]; v1.layer.borderWidth = 2; v1.layer.borderColor = [UIColor redColor].CGColor; v1.translatesAutoresizingMaskIntoConstraints = NO; [self.view addSubview:v1]; [NSLayoutConstraint activateConstraints: @[[v1.topAnchor constraintEqualToAnchor:self.view.topAnchor constant:100], [v1.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor], [v1.heightAnchor constraintEqualToConstant:40], ]]; NSInteger n = 6; // change this number as desired NSMutableArray* marr = [NSMutableArray new]; [marr addObject:v1]; for (NSInteger i = 1; i < n; i++) { UIView* v = [[UIView alloc] init]; v.layer.borderWidth = 2; v.layer.borderColor = [UIColor redColor].CGColor; v.translatesAutoresizingMaskIntoConstraints = NO; [self.view addSubview:v]; [marr addObject:v]; } for (NSInteger i = 1; i < n; i++) { UIView* v = marr[i]; UIView* prev = marr[i-1]; [NSLayoutConstraint activateConstraints: @[[v.topAnchor constraintEqualToAnchor:v1.topAnchor], [v.bottomAnchor constraintEqualToAnchor:v1.bottomAnchor], [v.leadingAnchor constraintEqualToAnchor:prev.trailingAnchor], [v.widthAnchor constraintEqualToAnchor:v1.widthAnchor] ]]; } UIView* v = marr[n-1]; [NSLayoutConstraint activateConstraints: @[[v.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor] ]];
每个NSLayoutConstraint只能关联两个视图,但是没有任何东西阻止你添加额外的约束。 例如:
[NSLayoutConstraint constraintWithItem:column[i-1] attribute: NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:column[i] attribute:NSLayoutAttributeWidth multiplied:1.f constant:0.f]; [NSLayoutConstraint constraintWithItem:column[i+1] attribute: NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:column[i] attribute:NSLayoutAttributeWidth multiplied:1.f constant:0.f];
如果添加这两个约束,则i-1,i和i + 1处的“列”将具有相同的宽度。
- UICollectionViewCell systemLayoutSizeFittingSize返回不正确的宽度
- 在UITableViewCell中加载UIView的Nib文件不能拉伸
- iOS滚动视图,容器视图 – 自动布局问题
- 在视图控制器的宽度上水平均匀分布UIButton的最简单的方法是什么?
- animationUIStackView排列的子视图内容大小更改
- 使用“自动布局”,如何使同一“行”上的两个标签在宽度上dynamic变化(根据每个标签的宽度进行调整)?
- NSLayoutConstraint并确定哪个子视图更宽
- 如何使用自动布局在UIPageViewController中定位子视图?
- 问题与iOS 8自动布局(代码在iOS 7完美的作品)