UIButton backgroundImage与图片

时间:2015-09-08 11:42:13

标签: ios objective-c image uibutton

我有UIButtons,我试图将图像设置为aspectFit。然而,使用Storyboard我遇到了一些困难,我将UIButton子类化并以编程方式将按钮的imageViews设置为ScaleAspectFit

#import "UIButtonWithImageAspectFit.h"

@implementation UIButtonWithImageAspectFit

-(void)awakeFromNib{
    [self.imageView setContentMode:UIViewContentModeScaleAspectFit];
}

@end

效果很好,按钮图像显示效果很好。

但是,现在我需要以编程方式交换按钮的图像,所以我尝试了:

[_firstLetterButton setImage:[UIImage imageNamed:@"2CeadLitir.png"]];

但这不起作用,所以根据建议我必须使用:

[_firstLetterButton setBackgroundImage:[UIImage imageNamed:@"2CeadLitir.png"] forState:UIControlStateNormal];

将图像作为backgroundImage添加到按钮。现在我必须在按钮中的图像。

  1. 可以很好地缩放为按钮的图像属性,
  2. 和另一个不能很好地缩放为背后显示的背景图像。
  3. 所以我回到了UIButton UIButtonWithImageAspectFit的子类 并尝试更改它,以便它设置backgroundImage的contentMode而不是图像

    但它似乎没有我可以访问的backgroundImage属性,但根据文档确实具有

    currentBackgroundImage
     Property
    

    但是,我无法在setContentMode

    上使用相同的方法currentBackgroundImage

    任何想法如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

您需要从Apple网站上考虑此插图。 enter image description here

来自Buttons tutorial。特别是:

  

<强>国家
  按钮有四种状态可配置为外观 - 默认,突出显示,选中和禁用。   并形成

UIButton class reference

  

讨论
  通常,如果没有为状态指定属性,则默认使用UIControlStateNormal值。如果未设置UIControlStateNormal值,则该属性默认为系统值。因此,您至少应该设置正常状态的值。

这是information about different UIControlState:

初学iOS Developer必须阅读所有这些链接。

答案 1 :(得分:1)

实际上UIButton有一个方法

- (void)setImage:(UIImage *)image
        forState:(UIControlState)state

所以我需要做的就是在UIButton而不是UIButton.imageView上设置图像时设置状态