简体   繁体   English

UIButton自动布局大小设置

[英]UIButton Autolayout size setting

I have a UIButton control placed in the view, there is a large background image set in the button, let's say the size of image is 600 x 300, and the size of button is 100 X 40, now I want to add the constraints to limit the width of button >= 100 and <= 200 depends on the title width. 我在视图中放置了一个UIButton控件,在按钮中设置了一个较大的背景图像,假设图像的大小为600 x 300,按钮的大小为100 X 40,现在我想添加约束到限制按钮的宽度> = 100和<= 200取决于标题的宽度。

The problem is that the button width always stretch to 200 instead of the actual title width, because the background image is too large than 200 pixel. 问题在于按钮的宽度始终拉伸到200,而不是实际的标题宽度,因为背景图像太大,不能超过200像素。 But what I want is to make the width fit with title other than the background image. 但是我想要的是使宽度适合背景图像以外的标题。

I have tried to reduce the priority of the button imageview in horizontal using setContentHuggingPriority and setContentCompressionResistancePriority, but unfortunately it doesn't work. 我尝试使用setContentHuggingPriority和setContentCompressionResistancePriority降低水平按钮图像视图的优先级,但不幸的是,它不起作用。 Please help!!! 请帮忙!!!

You should create an IBOutlet for a width constraint for your button then you can say something like: 您应该为按钮的宽度约束创建一个IBOutlet,然后可以这样说:

self.buttonWidthConstraint.constant = button.titleLabel?.sizeThatFits(button.frame.size).width

Or if you need it in objective-c: 或者,如果您在Objective-C中需要它:

self.buttonWidthConstraint.constant = [self.button.titleLabel sizeThatFits:self.button.frame.size].width;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM