将图像添加到我的UIButton子视图

时间:2015-02-23 08:05:14

标签: ios objective-c uibutton subview

我有一个UIButton作为子视图添加到我的超级视图中,它只是一个大块,如何将图像添加到我的按钮。

- (void)viewDidLoad
{

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(890, 345 , 100, 100);
button.backgroundColor = [UIColor purpleColor];

[self.collectionView.superview addSubview:button];
[button addTarget:self action:@selector(changeContentOffset:) forControlEvents:UIControlEventTouchUpInside];
}

6 个答案:

答案 0 :(得分:2)

您可以通过以下两种方式添加image in UIButton

1)借助设置Background Image

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(890, 345 , 100, 100);
    button.backgroundColor = [UIColor purpleColor];
    [button setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [self.collectionView.superview addSubview:button];
    [button addTarget:self action:@selector(changeContentOffset:) forControlEvents:UIControlEventTouchUpInside];

2)或者您可以将UIImageView添加为subview

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(890, 345 , 100, 100);
    button.backgroundColor = [UIColor purpleColor];
    [button setClipsToBounds:YES];
    [button setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    UIImageView * imgView = [[UIImageView alloc]init];
    [imgView setImage:[UIImage imageNamed:@""]];
    [imgView setFrame:CGRectMake(0, 0, 100, 100)];
    [button addSubview:imgView];    
    [self.collectionView.superview addSubview:button];
    [button addTarget:self action:@selector(changeContentOffset:) forControlEvents:UIControlEventTouchUpInside];

答案 1 :(得分:0)

使用此:     -setBackgroundImage:forState:

答案 2 :(得分:0)

如果你想要一个"图像作为按钮"你可以寻找这样的东西。而且不仅是带有图像的默认按钮

BOOL ipad = UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad;
UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];;
CGRect frame;
//universal app 
if (ipad)
{
    btn.frame = frame = CGRectMake( x, y, w, h );
}
else
{
    btn.frame = frame = CGRectMake( x, y, w, h );
}
btn.titleLabel.backgroundColor = [UIColor clearColor];
forState:UIControlStateNormal];

[btn setBackgroundImage:[UIImage imageNamed:@"buttonAsImage.png"] forState:UIControlStateNormal && UIControlStateHighlighted];
[btn setTitle:title forState:UIControlStateNormal];

答案 3 :(得分:0)

有不同的方法可以做到这一点。 首先,您可以在您的超级视图中添加imageview,并根据需要设置imageview的图像。然后,在同一位置添加具有imageview大小的按钮,并将按钮颜色设置为clearColor。但您需要先添加imageView,否则您的按钮将位于图像下方。

第二个是默认图像到按钮,使用setImage:image forState:UIControlStateNormal或setBackgroundImage:image forState:UIControlStateNormal。

答案 4 :(得分:0)

知道了,方法如下:

[button setBackgroundImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal && UIControlStateHighlighted];

答案 5 :(得分:0)

使用this method - (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state