使用可视布局约束在Swift中创建自定义按钮

时间:2015-07-09 20:01:03

标签: ios swift user-interface

    //signup button
    let signupButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
    signupButton.setTranslatesAutoresizingMaskIntoConstraints(false)
    signupButton.setBackgroundImage(UIImage(named: "signupButton"), forState: .Normal)
    signupButton.setTranslatesAutoresizingMaskIntoConstraints(false)
    signupButton.setTitleColor(UIColor(red: 1, green: 1, blue: 1, alpha: 1), forState: .Normal)
    signupButton.setTitle(NSLocalizedString("Sign Up", comment: ""), forState: .Normal)
    // align SignupButton from the top and bottom
    signupButton.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-464.5-[SignupButton]-142.5-|", options: .DirectionLeadingToTrailing, metrics: nil, views: ["signupButton": signupButton]))

    // align SignupButton from the left and right
    signupButton.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-196-[SignupButton]-30-|", options: .DirectionLeadingToTrailing, metrics: nil, views: ["signupButton": signupButton]))
    self.view.addSubview(signupButton)

这就是我所拥有的,当我注释掉约束时会创建按钮,但是我需要将约束置于正确的位置。

1 个答案:

答案 0 :(得分:0)

您必须在添加约束之前添加signupButton作为子视图,并且应将约束添加到包含signupButton的视图中,在这种情况下为self.view。此外,您的视图字典中的键是signupButton(以小写字母开头),但在格式字符串中,您使用的是SignupButton(以大写字母开头)。

let signupButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
signupButton.setTranslatesAutoresizingMaskIntoConstraints(false)
signupButton.setBackgroundImage(UIImage(named: "signupButton"), forState: .Normal)
signupButton.setTranslatesAutoresizingMaskIntoConstraints(false)
signupButton.setTitleColor(UIColor(red: 1, green: 1, blue: 1, alpha: 1), forState: .Normal)
signupButton.setTitle(NSLocalizedString("Sign Up", comment: ""), forState: .Normal)

self.view.addSubview(signupButton)

self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-464.5-[signupButton]-142.5-|", options: .DirectionLeadingToTrailing, metrics: nil, views: ["signupButton": signupButton]))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-196-[signupButton]-30-|", options: .DirectionLeadingToTrailing, metrics: nil, views: ["signupButton": signupButton]))