Snorlax
Snorlax

Reputation: 4735

Swift, Xcode: Changing UIButton Background and Text on Click

I want to change the background and text of the button on click, I tried several SO solutions but they haven't worked, you can see what I tried in my project: https://github.com/jzhang172/modalTest

I tried debugging it by putting a simple print statement and it looks like it doesn't ever go to it.

Upvotes: 0

Views: 1376

Answers (3)

Coder1000
Coder1000

Reputation: 4461

SOLUTION:

1) Create an IBAction from your UIButton and also an IBOutlet called button.

EDIT: As per your request (How to trigger the even when the button is TOUCHED, not RELEASED?):

enter image description here

2) Do this:

@IBAction func changes (sender: UIButton) {

    button.backgroundColor = UIColor.blueColor()

    button.setTitle("Button Title", forState: UIControlState.Normal)

}

Upvotes: 2

mc01
mc01

Reputation: 3770

Your UIButton @IBOutlet closePop is hooked up to a single @IBAction of the exact same name (closePop()). That closePop() IBAction ONLY dismisses the helpViewController - it doesn't do anything about the text or button color.

Your other @IBAction function like, in which you try to set the color & print "Is this even working?", is not hooked up to the button, and is never called.

Upvotes: 2

Geoherna
Geoherna

Reputation: 3534

UIButton's have a method for setting the title color. So if you had a UIButton IBOutlet named myBtn:

myBtn.setTitleColor(UIColor.blackColor(), forState: .Highlighted)

and to change the text of the button on touch:

myBtn.setTitle("This button was touched", forState: .Highlighted)

As far as setting the background color, you could add an extension for your UIButton which allows you to do this:

extension UIButton {
    private func imageWithColor(color: UIColor) -> UIImage {
        let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()

        CGContextSetFillColorWithColor(context, color.CGColor)
        CGContextFillRect(context, rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }

    func setBackgroundColor(color: UIColor, forUIControlState state: UIControlState) {
        self.setBackgroundImage(imageWithColor(color), forState: state)
    }
}

Then you could do:

myBtn.setBackgroundColor(UIColor.grayColor(), forUIControlState: .Highlighted)

Hope this helps!

Upvotes: 4

Related Questions