Making a UIButton a % of the screen size

前端 未结 4 1457
再見小時候
再見小時候 2021-01-13 00:57

I noticed certain button sizes look great on one the iPhone 5 simulator but do not look as good on the iPhone 6 simulator and this is because the heights or constraints that

相关标签:
4条回答
  • 2021-01-13 01:16

    This function gives you the bounds of the screen

    var bounds = UIScreen.mainScreen().bounds

    And then you can set the button width multipliying 0.4 x bounds.size.width

    Regards

    0 讨论(0)
  • 2021-01-13 01:16

    Swift 4.2

    In code it's really easy:

    override func viewDidLoad() {
            super.viewDidLoad()
    
            view.addSubview(button)
            button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
            button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    
            button.widthAnchor.constraint(equalToConstant: 100).isActive = true
            button.heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.height * 0.4).isActive = true
        }
    

    or use this instead of current heightAnchor:

    button.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.4).isActive = true
    

    hope this help :)

    
    
    0 讨论(0)
  • 2021-01-13 01:34
    1. Ctrl drag from button to superview and select Equal Widths
    2. Open Size Inspector edit Equal Widths constraint and set multiplier to 0.4. And you will see something like this: enter image description here

    3. Add missing constraints and update frames.

    enter image description here

    0 讨论(0)
  • 2021-01-13 01:41

    You can't set a constraint to be 40% of the screen height. However, if the button always has a 20px leading and trailing to the superview you could use that width and set an aspect ratio height.

    Another way could be to use UIScreen.mainScreen().bounds.size.height * 0.4 for your button height.

    A third way is to use the button's superview to set the height. Assuming that your button is a direct child of a UIViewController's view: view.bounds.size.height * 0.4.

    There's probably a bunch of other ways to do this as well but none of them will involve setting the height to an actual percentage as far as I'm aware.

    0 讨论(0)
提交回复
热议问题