uibutton与图像

Mau*_*lik 2 iphone uibutton

我有一个使用IB的按钮.现在我想以编程方式向按钮添加图像.如何设置按钮的图像尺寸大小,就像我们在IB布局 - >尺寸适合中一样.我想以编程方式进行

谢谢..

Kyl*_*yle 9

您可以使用图像添加到按钮UIButtonsetImage:forState:方法,然后你设置使用内容大小UIViewcontentMode属性.

一个例子看起来像这样:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *img = [UIImage imageNamed:@"myImage.png"];

button.frame = CGRectMake(20, 100, img.size.width, img.size.height);

[button setImage:img forState:UIControlStateNormal];
[button setImage:img forState:UIControlStateHighlighted];
[button setImage:img forState:UIControlStateSelected];

button.contentMode = UIViewContentModeScaleToFill; //Look up UIViewContentMode in the documentation for other options

[self.view addSubview:button];
Run Code Online (Sandbox Code Playgroud)