Get variable height for a UIButton for iPhones 5/6/6+

泄露秘密 提交于 2019-12-24 02:18:15

问题


For my 1) portrait only 2) deployment target iOS7/iOS8 app, I have in my design UIButtons which have variable heights, for iPhone 5, iPhone 6 and iPhone 6+. I am trying to use auto layout for this. (Not using size classes though).

Using auto layout how can I specify variable height for UIButton for these 3 screen sizes. The buttons look fine on iPhones 5* models, but thinner on iphone 6/6+. Now in auto layout I can say height >= or = or <= say 55), but how do I specify 44 for iphone5, 55 for iphone6, 66 for iphone6+?

Is this something that I can achieve using only auto layout or do I need to manupulate (frames) it in code? What is the point of me using auto layout then?

In addition to frames my designs also specify different font sizes. How do I go about this. Any best known methods for this, Stack-O friends .. ??


回答1:


It sounds like you need to be modifying the height constraints constant value.

In your xib/storyboard, create an outlet to your view/controller for the height constraint.

At runtime, probably in viewDidLoad, you will work out which device you're on, and then just change the constant of the height constraint.

CGFloat height;

// if iPhone 5
// height = 44
// else..........

self.buttonHeightConstraint.constant = height;

This will automatically trigger a flag that tells AutoLayout to recalculate frames and layout the view again.




回答2:


You are correct to ask "what is the point of auto-layout if I have to manipulate frames directly"? Thankfully, you don't have to.

An easy way of doing it is specifying the height in relation to a view of standard height (think a view that fits the whole screen).

For example, we can set our button's height to equal half the height of the view.

This way, the button is always going to scale with the view, either upwards or downwards (size-wise). Auto-layout will guarantee that the relation between them will always be 1/2.

Now the button will be half the size of its superview, regardless of size.




回答3:


I managed this by adding a Height-Constraint to the UIButton. Make an Outlet and you can set the Height in your UIViewController subclass with _myConstraint.constant = 55;



来源:https://stackoverflow.com/questions/28464848/get-variable-height-for-a-uibutton-for-iphones-5-6-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!