我有一個使用IB的按鈕。現在我想以編程方式將圖像添加到按鈕。我如何設置圖像大小的按鈕大小,就像我們在IB Layout - > Size to Fit中所做的那樣。我想這樣做編程帶圖像的uibutton
謝謝..
我有一個使用IB的按鈕。現在我想以編程方式將圖像添加到按鈕。我如何設置圖像大小的按鈕大小,就像我們在IB Layout - > Size to Fit中所做的那樣。我想這樣做編程帶圖像的uibutton
謝謝..
您可以將圖像添加到使用UIButton
的setImage:forState:
方法按鈕,然後設置使用UIView
內容上漿的contentMode
屬性。
一個例子是這樣的:
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:UIControlStateHilighted];
[button setImage:img forState:UIControlStateSelected];
button.contentMode = UIViewContentModeScaleToFill; //Look up UIViewContentMode in the documentation for other options
[self.view addSubview:button];
示例代碼,
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *img1 = [UIImage imageNamed:@"image1.png"];
btn.frame = CGRectMake(20.0 , 270.0, img1.size.width, img1.size.height);
[btn setImage:img1 forState:UIControlStateNormal];
UIImage *img2 = [UIImage imageNamed:@"image2.png"];
[btn setImage:img2 forState:UIControlStateHighlighted];
[btn setImage:img2 forState:UIControlStateSelected];
[btn addTarget:self action:@selector(Action:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
[yourButton setImage:yourImage forState:UIControlStateNormal];
yourButton.contentMode = UIViewContentModeScaleToFill;
其中用於contentMode
的值可以爲
typedef enum {
UIViewContentModeScaleToFill,
UIViewContentModeScaleAspectFit, // contents scaled to fit with fixed aspect. remainder is transparent
UIViewContentModeScaleAspectFill, // contents scaled to fill with fixed aspect. some portion of content may be clipped.
UIViewContentModeRedraw, // redraw on bounds change (calls -setNeedsDisplay)
UIViewContentModeCenter, // contents remain same size. positioned adjusted.
UIViewContentModeTop,
UIViewContentModeBottom,
UIViewContentModeLeft,
UIViewContentModeRight,
UIViewContentModeTopLeft,
UIViewContentModeTopRight,
UIViewContentModeBottomLeft,
UIViewContentModeBottomRight,
} UIViewContentMode;
我認爲這可以幫助你
使用UIButton的方法sizeToFit(UIView act ually)。
謝謝分享! – swiftBoy 2014-10-15 11:17:32
對於那些從這個解決方案複製和粘貼,他拼寫錯誤'UIControlStateHighlighted'。 – GantMan 2015-10-25 22:10:23