我正在使用此代码在swift中创建我的按钮。它工作得很好,除了我不知道如何从代码中添加约束。
let button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(100, 100, 100, 50)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Test Button", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
我想将按钮放置在50左右,从顶部放置100。 任何帮助将不胜感激。
答案 0 :(得分:1)
试试:
....
self.view.addSubview(button)
button.setTranslatesAutoresizingMaskIntoConstraints(false)
let views = ["button": button]
var constraintHorizontal = NSLayoutConstraint.constraintsWithVisualFormat("H:|-50-[button]", options: NSLayoutFormatOptions(0), metrics: nil, views: views)
view.addConstraints(constraintHorizontal)
var constraintWertical = NSLayoutConstraint.constraintsWithVisualFormat("V:|-100-[button]", options: NSLayoutFormatOptions(0), metrics: nil, views: views)
view.addConstraints(constraintWertical)