sanjana
sanjana

Reputation: 3034

Change alpha of imageview of UIButton

Is there any way to change alpha of UIButton's imageview? I already tried subclassing UIButton and do below code, but it doesn't work.

self.imageView.alpha = 0.0;

I know it can be done by adding external UIImageView as a subview to UIButton but I want to know if its possible without it. Thanks!

Upvotes: 3

Views: 4336

Answers (5)

Steve Tinx
Steve Tinx

Reputation: 1

I needed something similar to this myself recently. I wanted to have a button where I could add an image as a background, and then have a semi-opaque colour overlay to the graphic so as to create a custom coloured image button type thing.

The way I found was to have:

  • UIImageView (to contain the image required)
  • UIView (to hold a colour with alpha=0.7ish)
  • UIButton colourless/transparent.

They all have the same size, width, position and are layered in the above order. That way you can dictate what the image will be (and its alpha if necessary), a coloured overlay on top of the image (with alpha as required), and then a transparent clickable button on top.

Upvotes: 0

mixel
mixel

Reputation: 25876

You can do it by changing alpha of an UIImage.

See this answer for the Swift version and this one for the Obj-C version.

Upvotes: 0

SwiftArchitect
SwiftArchitect

Reputation: 48542

With subclass (will survive layout changes):

override func layoutSubviews() {
    super.layoutSubviews()
    if let imageView = imageView {
        imageView.alpha = 0.2
    }
}

Without subclass (transient, suitable to animations):

if let imageView = imageButton.imageView {
    imageView.alpha = CGFloat(sender.value)
}

Subclass Source Code

@IBDesignable class FadeButton: UIButton {

    @IBInspectable var imageAlpha: CGFloat = 1 {
        didSet {
            if let imageView = imageView {
                imageView.alpha = imageAlpha
            }
        }
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        if let imageView = imageView {
            imageView.alpha = imageAlpha
        }
    }
}

Invoke with imageButton.imageAlpha = alpha

Demo

Fade demo

► Find this solution on GitHub and additional details on Swift Recipes.

Upvotes: 3

Tobi Nary
Tobi Nary

Reputation: 4596

To conclude the comments on both other answers: subclassing and/or adding another UIImageView is the simplest choice to archieve persistent, reliant behaviour.

Upvotes: 1

user5846743
user5846743

Reputation:

Probably a hacky way

for (UIView *view in myButton.subviews) {
    if ([view isKindOfClass:[UIImageView class]]) {
          view.alpha = 0.5;
    }
}

Upvotes: 4

Related Questions