设置UIButton背景的alpha但不是标题

问题描述 投票:20回答:7

当我设置按钮的alpha时,它也会影响标题的不透明度。有没有办法只定位背景并将标题alpha保留为1.0?

ios xcode uibutton
7个回答
24
投票

这对我有用:

self.myButton.backgroundColor = [UIColor clearColor];

或者如果您不想完全清楚,但仍然具有透明度,您可以使用:

self.myButton.backgroundColor = [UIColor colorWithRed:200.0/255.0 green:200.0/255.0 blue:200.0/255.0 alpha:0.5];

第二个例子会给你灰色的alpha 0.5。

SWIFT 4更新

myButton.backgroundColor = .clear

要么

myButton.backgroundColor = UIColor(red: 200.0/255.0, green: 200.0/255.0, blue: 200.0/255.0, alpha:0.5)

18
投票

您还可以更改故事板中颜色的alpha值,

见附图:

change alpha of color in storyboard/interface builder


8
投票

在Swift中:

import UIKit

class SignInUpMenuTableViewControllerBigButton: UIButton {

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.applyCustomDesign()
    }

    func applyCustomDesign() {
        // We set the background color of the UIButton.
        self.clearHighlighted()
    }

    override var highlighted: Bool {
        didSet {
            if highlighted {
                self.highlightBtn()
            } else {
                self.clearHighlighted()
            }
        }
    }

    func highlightBtn() {
        self.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.0)
    }

    func clearHighlighted() {
        self.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.05)
    }

}

Swift 4.2

import UIKit

class SignInUpMenuTableViewControllerBigButton: UIButton {

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.applyCustomDesign()
    }

    func applyCustomDesign() {
        // We set the background color of the UIButton.
        self.clearHighlighted()
    }

    override var highlighted: Bool {
        didSet {
            if highlighted {
                self.highlightBtn()
            } else {
                self.clearHighlighted()
            }
        }
    }

    func highlightBtn() {
        self.backgroundColor = UIColor.whiteColor().withAlphaComponent(0.0)
    }

    func clearHighlighted() {
        self.backgroundColor = UIColor.whiteColor().withAlphaComponent(0.05)
    }

}

1
投票

对UIButton进行子类化并扩展setEnabled:方法似乎有效:

- (void) setEnabled:(BOOL)enabled {    
    [super setEnabled:enabled];
    if (enabled) {
        self.imageView.alpha = 1;
    } else {
        self.imageView.alpha = .25;
    }
}

0
投票

使用UIButton,您可以通过将按钮样式设置为Custom而不是Round Rect来删除背景。这使标题保持完整,但删除了按钮背景。如果您在Storyboards中执行此操作,则可以更改元素属性中的按钮样式。对于代码,格式为:

UIButton *button = [[UIButton alloc] buttonWithType:UIButtonTypeCustom];
// Setup frame and add to view

0
投票

斯威夫特button.backgroundColor = UIColor.white.withAlphaComponent(0.7)


-1
投票

你只是使用纯色作为背景吗?或者你正在使用图像?

如果您正在使用图像,那么您可以使用内置alpha的图像。

如果您使用的是颜色,则可以在颜色上设置alpha。

但是,更改任何视图的alpha会影响所有子视图。

© www.soinside.com 2019 - 2024. All rights reserved.