uibutton с изображением

#iphone #uibutton

#iPhone #uibutton

Вопрос:

У меня есть кнопка, использующая IB. Теперь я хочу добавить изображение к кнопке программно. как я могу установить размер кнопки для размера изображения, как мы делаем в IB Layout -> Size to Fit. Я хочу сделать это программно

Спасибо..

Ответ №1:

Вы можете добавить изображение к кнопке с помощью 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:UIControlStateHighlighted];
[button setImage:img forState:UIControlStateSelected];

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

[self.view addSubview:button];
  

Комментарии:

1. Для тех, кто копирует и вставляет из этого решения, он написал UIControlStateHighlighted неправильно.

Ответ №2:

 [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;
  

Я думаю, это могло бы вам помочь

Ответ №3:

Пример кода,

 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];
  

Ответ №4:

Используйте метод sizeToFit UIButton (фактически UIView).