我想创建一个横向级联的对象数组,我试图创建一个函数来减少我的代码的大小,但是,似乎可能有一个NSLayoutConstraint之间的冲突创建的对象可能是?以编程方式创建一个swift对象数组3
这里是我的代码
private func createProfileImageContainers(numberOfFriends: Int) {
for friends in 1...numberOfFriends {
let imageViewContainer = UIView()
imageViewContainer.translatesAutoresizingMaskIntoConstraints = false
imageViewContainer.backgroundColor = UIColor.blue
imageViewContainer.frame = CGRect(x: 0, y: 0, width: frame.width/10, height: frame.width/10)
NSLayoutConstraint(item: imageViewContainer, attribute: .centerX, relatedBy: .equal, toItem: container, attribute: .centerX, multiplier: CGFloat((1/2) + ((friends - 1)/50)), constant: 0).isActive = true
NSLayoutConstraint(item: imageViewContainer, attribute: .centerY, relatedBy: .equal, toItem: container, attribute: .centerY, multiplier: 1, constant: 0).isActive = true
addSubview(imageViewContainer)
}
}
下面是调试器说
0的乘数或与对第一属性的位置的零秒在一起的项目将创建等于一个位置的非法拘禁不变。位置属性必须成对指定。'
有什么建议吗?
编辑:
感谢抢劫的答案,我能够与调试然而imageViewContainer只有一个实例正在加入到解决问题。可能是因为它们都被添加到具有相同名称的视图层次结构中,因此每个新视图都取代了最后一个视图... 我认为创建一个类将解决此问题,但现在我无法获取任何内容。
这里是更新的代码...
class profileImageContainer: UIView {
let imageViewContainer: UIView = {
let iv = UIView()
iv.translatesAutoresizingMaskIntoConstraints = false
iv.backgroundColor = UIColor.blue
return iv
}()
}
private func createProfileImageContainers(numberOfFriends: Int) {
for friends in 1...numberOfFriends {
print(friends)
let imageViewContainer = profileImageContainer()
addSubview(imageViewContainer)
NSLayoutConstraint(item: imageViewContainer, attribute: .width, relatedBy: .equal, toItem: container, attribute: .width, multiplier: 0.1, constant: 0).isActive = true
NSLayoutConstraint(item: imageViewContainer, attribute: .height, relatedBy: .equal, toItem: container, attribute: .width, multiplier: 0.1, constant: 0).isActive = true
NSLayoutConstraint(item: imageViewContainer, attribute: .centerX, relatedBy: .equal, toItem: container, attribute: .centerX, multiplier: 0.5 + (CGFloat(friends - 1)/50.0), constant: 0).isActive = true
NSLayoutConstraint(item: imageViewContainer, attribute: .centerY, relatedBy: .equal, toItem: container, attribute: .centerY, multiplier: 1, constant: 0).isActive = true
}
}
喜欢的UITableView或UIStackView的一样。 – luckyShubhra
不应该'centerX'乘数乘以容器的宽度? – NRitH
@NRitH乘数是一个乘数,它可以是任何数字。在那里的代码只是一个占位符atm,但它仍然应该是有效的。我只是想测试for循环。 – Stefan