我现在正在做这样的事情:
startButton.frame = CGRectMake(0, 0, startButton.frame.width, startButton.frame.height)
viewDidLoad
中的。然而,这似乎没有任何区别。
做这种事的正确方法是什么?
答案 0 :(得分:2)
如果不使用AutoLayout
,请使用此更改位置var X_Position:CGFloat? = 50.0 //use your X position here
var Y_Position:CGFloat? = 50.0 //use your Y position here
startButton.frame = CGRectMake(X_Position, Y_Position, startButton.frame.width, startButton.frame.height)
答案 1 :(得分:1)
嗯,设置按钮位置的最佳方法是使用约束!这里有一些我用过的:)
```swift
let storeBtnImg = UIImage(named: "StoreButton")
storeBtn.translatesAutoresizingMaskIntoConstraints = false
storeBtn.frame = CGRect(origin: CGPointMake(self.frame.width / 7.8, self.frame.height / 1.9), size: CGSize(width: self.frame.width / 10, height: self.frame.height / 10))
storeBtn.backgroundColor = nil
storeBtn.addTarget(self, action: "storeBtnAction", forControlEvents: .TouchUpInside)
storeBtn.setImage(storeBtnImg, forState: UIControlState.Normal)
self.view?.addSubview(storeBtn)
NSLayoutConstraint(item: storeBtn, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: storeBtn, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -75).active = true ```
设置.translatesAutoresizingMaskIntoConstraints = false
并将.active = true
放在约束的末尾
希望这有帮助,祝你好运!
答案 2 :(得分:0)
我个人更喜欢以编程方式完成所有UI。一个例子是:
// Button declaration
private lazy var upVoteButton: UIButton = {
let btn = UIButton()
btn.addTarget(self, action: #selector(anObjcActionSelector), for: .touchUpInside)
btn.translatesAutoresizingMaskIntoConstraints = false
return btn
}()
// Method that configures your views
private func configureLayout() {
addSubview(upVoteButton)
NSLayoutConstraint.activate([
upVoteButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
upVoteButton.heightAnchor.constraint(equalToConstant: 32),
upVoteButton.topAnchor.constraint(equalTo: view.topAncher, constant: 32)
// You can trust some attributes, like the width, to autolayout if you want
])
}
您可以看看constraint
方法documentation,它非常完整。
您也可以使用SnapKit。如果您要完全通过编程来编写大型应用程序,则可以避免使用一些无聊的繁琐代码。