我正在创建一组简单的UIImageViews,它们都使用相同的图像,并在屏幕上垂直均匀分布。最初我只是硬编码每个视图的创建,但我想让它更紧凑,因为它们都是相同的图像。
这是我当前的代码,XCode正在抱怨(EXC_BAD_INSTRUCTION)。 loadingView是一个用于将所有图像组合在一起的UIView。
let items = [UIImageView?](count:7, repeatedValue: nil)
for item in items {
item!.image = UIImage(named: "loading_items")
}
// could potentially iterate through this too
self.loadingView.addSubview(items[0]!)
items[0]!.autoPinEdgeToSuperviewEdge(.Top)
self.loadingView.addSubview(items[1]!)
items[1]!.autoPinEdge(.Top, toEdge: .Bottom, ofView: items[0]!, withOffset: 12)
self.loadingView.addSubview(items[2]!)
items[2]!.autoPinEdge(.Top, toEdge: .Bottom, ofView: items[1]!, withOffset: 12)
self.loadingView.addSubview(items[3]!)
items[3]!.autoPinEdge(.Top, toEdge: .Bottom, ofView: items[2]!, withOffset: 12)
self.loadingView.addSubview(items[4]!)
items[4]!.autoPinEdge(.Top, toEdge: .Bottom, ofView: items[3]!, withOffset: 12)
self.loadingView.addSubview(items[5]!)
items[5]!.autoPinEdge(.Top, toEdge: .Bottom, ofView: items[4]!, withOffset: 12)
self.loadingView.addSubview(items[6]!)
items[6]!.autoPinEdge(.Top, toEdge: .Bottom, ofView: items[5]!, withOffset: 12)
for item in items {
item!.autoAlignAxis(.Vertical, toSameAxisOfView: loadingView) // uses AutoLayout
}
我想知道这段代码有什么问题,以及是否有更高效的“Swift-y”方式来做这件事。
答案 0 :(得分:0)
使用UIStackView并将您的UIImageView添加为堆栈视图的子视图,并将stackview添加为superview的子视图。这将使您的工作变得轻松 // ImageView(view1,view2,view3)
UIImageview *view1 = [[UIImageview alloc] init];
view1.backgroundColor = [UIColor blueColor];
[view1.heightAnchor constraintEqualToConstant:100].active = true;
[view1.widthAnchor constraintEqualToConstant:120].active = true;
UIStackView *stackView = [[UIStackView alloc] init];
stackView.axis = UILayoutConstraintAxisVertical;
stackView.distribution = UIStackViewDistributionEqualSpacing;
stackView.alignment = UIStackViewAlignmentCenter;
stackView.spacing = 30;
[stackView addArrangedSubview:Imageview1];
[stackView addArrangedSubview:Imageview2];
[stackView addArrangedSubview:Imageview3];
stackView.translatesAutoresizingMaskIntoConstraints = false;
[self.view addSubview:stackView];
//Layout for Stack View
[stackView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = true;
[stackView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = true;