How can I set a button background color on iPhone?

后端 未结 18 2031
予麋鹿
予麋鹿 2020-11-30 20:22

How can I set a custom background color of a button?

Interface Builder doesn\'t seem to have an interface to do this.

Is it only available programmatically

18条回答
  •  时光取名叫无心
    2020-11-30 20:53

    I found that I needed to use a stretchable image to accomplish this. Apple's UICatalog example has one or more colored buttons that are drawn in this fashion. You could use their template image and recolor it to suit your button needs.

    I'm not sure about doing this in Interface Builder, but I was able to create a button and use an image for its contents using the following code:

    downloadButton = [[UIButton alloc] initWithFrame:CGRectMake(36, 212, 247, 37)];
    
    downloadButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    downloadButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    
    [downloadButton setTitle:NSLocalizedStringFromTable(@"Download", @"Localized", nil) forState:UIControlStateNormal]; 
    [downloadButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [downloadButton setFont:[UIFont boldSystemFontOfSize:14.0]];
    
    UIImage *newImage = [[UIImage imageNamed:@"greenButton.png"] stretchableImageWithLeftCapWidth:12.0f topCapHeight:0.0f];
    [downloadButton setBackgroundImage:newImage forState:UIControlStateNormal];
    
    [downloadButton addTarget:self action:@selector(downloadNewItem) forControlEvents:UIControlEventTouchDown];
    
    downloadButton.backgroundColor = [UIColor clearColor];
    [downloadDisplayView addSubview:downloadButton];
    

提交回复
热议问题