如何在按钮alpha也设置的情况下更改UIButton的alpha

时间:2014-06-21 12:28:25

标签: ios objective-c uibutton

如图所示,我有2个0.5 alpha和1 alpha的按钮。我想将第一张图片中标题的alpha值更改为1.这可能吗?

到目前为止,我尝试了一些不起作用的内容:

button.titleLabel.alpha = 1;  
[button setTitleColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:1] forState:UIControlStateNormal];

enter image description here

UIButton *button = (UIButton *)view;
if(self.currentArray[index][2] != NULL) //before it was if (button == nil)
{
    NSString *name = [[NSString alloc] initWithString:self.currentArray[index][2]];
    UIImage *image = [UIImage imageNamed:self.currentArray[index][5]];
    button = [UIButton buttonWithType:UIButtonTypeCustom];

    int extraLeftInset = 0;
    if ([self.currentArray[index][6] isEqualToString:@"true"]) {
        //show it
    }else if([self.currentArray[index][7] isEqualToString:@"true"]){

    }else{
        UIImage *locked = [UIImage imageNamed:@"fruitify_locked.png"];
        button.imageEdgeInsets = UIEdgeInsetsMake(15, 15, 15, 15);
        [button setImage:locked forState:UIControlStateNormal];
        extraLeftInset = - 256; //size of locked
        button.backgroundColor = [UIColor clearColor];
        button.alpha = 0.5;
    }

    button.frame = CGRectMake(0.0, 0.0, 56, 56);
    button.tag = index;

    [button setBackgroundImage:image forState:UIControlStateNormal];

    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    UIEdgeInsets buttonInset = UIEdgeInsetsMake(30, -2 + extraLeftInset, -20, -2);
    [button setTitleEdgeInsets:buttonInset];
    [button setTitle:name forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize: 8];
    button.titleLabel.lineBreakMode   = NSLineBreakByWordWrapping;


    [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
}

2 个答案:

答案 0 :(得分:2)

执行此操作的一种方法是调整图像的Alpha值。这可以通过将图像传递给此方法来完成,

-(UIImage *)image:(UIImage *) image  withAdjustedAlpha:(CGFloat) newAlpha{
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0);
    [image drawAtPoint:CGPointZero blendMode:kCGBlendModeCopy alpha:newAlpha];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

答案 1 :(得分:0)

Alpha设置会影响视图及其所有子视图。如果在按钮上设置alpha,按钮的每个部分都将具有该alpha值。

您有几种可能的选择。

您可以创建UIButton的自定义子类,该子类管理UILabel,该UILabel是视图层次结构中按钮的同级视图。然而,这会在几个方面变得混乱。正常的按钮标题方法不起作用,如果按钮被删除,您必须引入自己的控制逻辑以从超视图中删除按钮标签

您也可以尝试操作按钮图像视图的alpha属性。 (按钮的imageView属性是只读的,但您仍然可以更改该属性中图像视图的属性。您需要进行测试以确保按钮不会弄乱图像视图的alpha属性它会交换不同按钮状态的图像(突出显示,选中等)。您可能还需要将按钮上的opaque属性设置为NO,也可能需要在图像视图上设置。(您需要进行实验。)

顺便说一句,我喜欢你使用setTitleEdgeInsets来抵消按钮标题的技巧。我以前没见过。