我以编程方式创建了一个带约束的按钮。但按钮移动到错误的位置(右下角)。我错了什么?
item = UIButton(type: .custom)
item.setImage(image, for: .normal)
item.addTarget(self, action: #selector(PlayController.itemAct(sender:)), for: .touchUpInside)
item.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(item)
// Constraints
item.widthAnchor.constraint(equalToConstant: 30).isActive = true
item.heightAnchor.constraint(equalToConstant: 30).isActive = true
item.topAnchor.constraint(equalTo: view.topAnchor, constant: 441).isActive = true
item.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 123).isActive = true
item.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 222).isActive = true
item.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 196).isActive = true
修改
如果您要创建左,右,上,下,您应将负值设置为item.trailingAnchor
和item.bottomAnchor
,对我有用。
答案 0 :(得分:0)
以下是我的一些代码通过约束的示例,因为有许多不同的方法。这是我最喜欢的方式之一:
containerView.addConstraints([
NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: containerView, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0),
NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: containerView, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: containerView, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: containerView, attribute: NSLayoutAttribute.right, multiplier: 1, constant: 0)
])
确保将约束添加到容器视图
另请注意,如果你喜欢它,你只想添加上/左/右/下或上/左/宽/高。你最多只需要4个(通常)