您可以設置框架的樣子,並將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)
])
據我所知,NSLayoutConstraint仍然在迅速2. API的一部分,你需要創建一些那些並將它們添加到'self.view'使用方法'addConstraint'('s')。 – dudeman
順便說一句,如果你使用'frame',就像Rob想要的那樣,你可能也想設置'autoresizingMask'。就個人而言,我會堅持約束。 – Rob