Раствор 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:
При использовании AutoLayout ограничения:
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