如何以编程方式为Swift 2中的按钮添加约束?

时间:2015-12-23 17:15:12

标签: ios swift2 constraints

我在这上面看到的所有问题都是针对swift 1.我试图创建一个按钮并为其添加约束。我希望按钮位于30 x和390 y。我还希望按钮的大小为75 x和75 y。我尝试的一切都没有奏效。请帮忙。下面是创建按钮的代码(你会看到我在按钮上添加了一个图像,所以我可以更好地看到它):

let button = UIButton(type: UIButtonType.System) as UIButton
button.setImage(UIImage(named: "BlueBall.png")!, forState:  U IControlState.Normal)
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)

谢谢。安东

1 个答案:

答案 0 :(得分:1)

您只需按照自己喜欢的方式设置框架,并将translatesAutoresizingMaskIntoConstraints设置为true。在你的情况下,这将是最简单的答案。

    let button = UIButton(type: UIButtonType.System)
    // button.translatesAutoresizingMaskIntoConstraints is true by default
    button.frame = CGRectMake(30, 390, 75, 75)
    button.setImage(UIImage(named: "BlueBall.png")!, forState: UIControlState.Normal)
    button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
    view.addSubview(button)

如果你真的想用限制来做,那就更需要工作了。如果您的部署目标是iOS 9.0或更高版本,则可以执行以下操作:

    let button = UIButton(type: UIButtonType.System)
    button.setImage(UIImage(named: "BlueBall.png")!, forState: UIControlState.Normal)
    button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
    view.addSubview(button)

    button.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activateConstraints([
        button.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor, constant: 30),
        button.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 390),
        button.widthAnchor.constraintEqualToConstant(75),
        button.heightAnchor.constraintEqualToConstant(75)
    ])