解决方案1:
通过使用UIView的帧作为参考
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let rect : CGRect = self.view.frame
let width = rect.width
let height = rect.height
let buttonHeight : CGFloat = 50.0
let leftMargin : CGFloat = 10.0
let bottomMargin : CGFloat = 10.0
let button : UIButton = UIButton()
button.frame = CGRectMake(leftMargin, height-buttonHeight-bottomMargin, width - 2*leftMargin , buttonHeight)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Add new request", forState: UIControlState.Normal)
self.view.addSubview(button)
}
}
解决方案2:
通过使用自动版式约束:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let requiredButton : UIButton = {
let button = UIButton()
button.backgroundColor = UIColor.greenColor()
button.setTitle("Add new request", forState: UIControlState.Normal)
return button
}()
// dont worry about frame right now
self.view.addSubview(requiredButton)
// set frame using autolayout
self.view.addContraintsWithFormat("H:|-10-[v0]-10-|", views: requiredButton)
self.view.addContraintsWithFormat("V:[v0(50)]-10-|", views: requiredButton)
[enter image description here][1]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension UIView{
func addContraintsWithFormat(format: String, views: UIView...){
var viewDictionary = [String: UIView]()
for (index,view) in views.enumerate(){
let key = "v\(index)"
viewDictionary[key] = view
view.translatesAutoresizingMaskIntoConstraints = false
}
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(format, options: NSLayoutFormatOptions(), metrics: nil, views: viewDictionary))
}
}
在这两种情况下输出相同
使用AutoLayout约束。我使用[SnapKit](https://github.com/SnapKit/SnapKit)来制作基于代码的约束条件并不容易。 – brandonscript
以及我需要显示和隐藏按钮的基础上,所以我需要以编程方式执行 – hellosheikh
是的,这就是为什么我提到了SnapKit - 编程约束,但不必编写令人讨厌,复杂的约束语法,你可以做到这一点使用它们的逻辑,基于块的语法。 – brandonscript