Crystal
Crystal

Reputation: 29498

UIButton with custom image not highlighting on selected

I have transparent image that I'm trying to use as the UIButton in code like this:

        settingsButton = UIButton(type: UIButtonType.Custom)
        settingsButton.translatesAutoresizingMaskIntoConstraints = false
        settingsButton.setImage(UIImage(named: "gear_icon.png"), forState: UIControlState.Normal)
        settingsButton.showsTouchWhenHighlighted = true
        settingsButton.addTarget(self, action: #selector(GameViewController.settingsButtonPressed(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(settingsButton)
        let topConstraint = settingsButton.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 10)
        let rightConstraint = settingsButton.rightAnchor.constraintEqualToAnchor(view.rightAnchor, constant: -10)
        NSLayoutConstraint.activateConstraints([topConstraint, rightConstraint])

When I select the button, the button does not become highlighted like standard UIButtons. Do you HAVE to provide a custom image for UIControlState.Selected? I saw some code that would let you provide this effect by creating a UIImage in code like this:

func imageWithColor(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context: CGContextRef = UIGraphicsGetCurrentContext()!
        CGContextSetFillColorWithColor(context, color.CGColor)
        CGContextFillRect(context, rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }

But when I looked at some example projects online that use custom images in IB, it doesn't look like they set any image for the UIControlState.Selected, yet the image for the UIButton becomes gray when the button is depressed so I was confused as to how that how was done.

Upvotes: 1

Views: 344

Answers (1)

Hayk Petrosyan
Hayk Petrosyan

Reputation: 373

I think your button didn't become highlighted ,because you customised it , I think you need add image for highlighted and pressed states, or change button type from custom to another type from UIButtonType and then set image for normal state , I think it will help

Upvotes: 0

Related Questions