简体   繁体   English

以编程方式更改UIButton大小-iOS

[英]Programmatically change UIButton size - iOS

I have a simple iOS application which is using the Google Plus iOS SDK. 我有一个使用Google Plus iOS SDK的简单iOS应用程序。 I want to customise the sign in button. 我要自定义登录按钮。 I have managed to get it looking how I want, but I can't get the button to be the size I want. 我设法使它看起来像我想要的,但是我无法使按钮成为我想要的尺寸。 (I am not using auto layout). (我没有使用自动布局)。 Here is my code in my viewDidLoad: 这是我的viewDidLoad中的代码:

[addservice_4 setImage:[UIImage imageNamed:@"uiTagFriendsAdd.png"] forState:UIControlStateNormal];
[addservice_4 setImage:[UIImage imageNamed:@"uiTagFriendsAdd.png"] forState:UIControlStateHighlighted];
[addservice_4 setImage:[UIImage imageNamed:@"uiTagFriendsAdd.png"] forState:UIControlStateSelected];
addservice_4.layer.cornerRadius = 5;
addservice_4.layer.borderWidth = 1.0f;
addservice_4.layer.borderColor = [[UIColor blueColor] CGColor];

Doing the above changes programmatically leaves me with this end result: 以编程方式进行上述更改会使我得到以下最终结果:

UIButton屏幕截图

As you can see the button is too wide. 如您所见,按钮太宽。 So I tried change its size programmatically but that does not work either: 因此,我尝试以编程方式更改其大小,但这也不起作用:

addservice_4.frame = CGRectMake(20, 22, 101, 30);

Is there any way to fix this? 有没有什么办法解决这一问题?

if you have to set the image property on UIButton Apple recommends using an image with the right size or double its size if using image assets. 如果必须在UIButton上设置image属性,Apple建议使用正确大小的图像,如果使用图像资产,则建议使用两倍大小的图像。

if that's not a good option for you, I guess you could get the setFrame: method to work as you'd expect in your question by using the setBackgroundImage:forState instead of setImage:forState like this: 如果这不是您的好选择,我想您可以通过使用setBackgroundImage:forState而不是setImage:forState来使setFrame:方法按您期望的那样工作:

[addservice_4 setBackgroundImage:[UIImage imageNamed:@"uiTagFriendsAdd.png"] forState:UIControlStateNormal];
[addservice_4 setBackgroundImage:[UIImage imageNamed:@"uiTagFriendsAdd.png"] forState:UIControlStateHighlighted];
[addservice_4 setBackgroundImage:[UIImage imageNamed:@"uiTagFriendsAdd.png"] forState:UIControlStateSelected];
addservice_4.layer.cornerRadius = 5;
addservice_4.layer.borderWidth = 1.0f;
addservice_4.layer.borderColor = [[UIColor blueColor] CGColor];
addservice_4.frame = CGRectMake(20, 22, 101, 30);

Using Autolayout in the end turned out to fix the problem (because I believe the constraints it puts in place stop the Google Plus SDK from making the button bigger). 最终使用Autolayout可以解决问题(因为我相信它所施加的限制会阻止Google Plus SDK增大按钮的大小)。 The only problem is that I now have to fix a mirage of other problems like support for 3.5 inch display and so on because Autolayout is truly horrible.... :( 唯一的问题是,我现在必须修复其他问题,例如对3.5英寸显示器的支持等等,因为Autolayout确实很可怕。...:(

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

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