Reputation: 23
I would like to make a button close to the bottom of the screen. If for ex. user's device is iPhone 5S, 10 points but for iPhone 11, 20 point etc. I couldn't find how to make it like
constraint = height / constant
so higher the device higher the button will be. How can I achieve this programmatically or from Xcode UI?
Upvotes: 0
Views: 65
Reputation: 6324
Maybe you can get the height of your devices' windows and multiply it for the ratio?
var button : UIButton = {
let b = UIButton()
b.translatesAutoresizingMaskIntoConstraints = false
b.backgroundColor = .red
return b
}()
override func viewDidLoad() {
super.viewDidLoad()
let screenSize = UIScreen.main.bounds
let height = screenSize.height
let ratio:CGFloat = 0.05 // you can change this
let bottomConstraint = height*ratio
print(bottomConstraint) // this would print 44.80 on the iPhone 11 and 33.35 on the iPhone 8
self.view.addSubview(button)
button.heightAnchor.constraint(equalToConstant: 50).isActive = true
button.widthAnchor.constraint(equalToConstant: 200).isActive = true
button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
// then you applied the variable constraint
button.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor, constant: -bottomConstraint).isActive = true
}
Upvotes: 1
Reputation: 1902
In your viewDidLoad
, get the reference for the view to setup as so:
class ViewController: UIViewController {
var targetView: UIView! // or @IBOutlet if you created it from the Interface Builder (IB)
private let ratio: CGFloat = 0.05
override func viewDidLoad() {
super.viewDidLoad()
// The following line enables you to programmatically set constraint using AutoLayout
targetView.translatesAutoresizingMaskIntoConstraints = false
// Get the height of the screen
let height = UIScreen.main.bounds.height
targetView.bottomAnchor.constraint(
equalTo: view.safeAreaLayoutGuide.bottomAnchor,
constant: -height * ratio
).isActive = true
// Set the other necessary constraints
}
Upvotes: 0