Monday, May 1, 2017

UIButton - Update button label when pressed

This post shows how to change the text/title of a button every time the button is pressed.
The code below is written in Swift 3.1 with Xcode 8.3.2 and tested with iOS 10.3.1.


import UIKit

class ViewController: UIViewController {
    var count : Int = 1
    override func viewDidLoad() {
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 200, height: 40)) =
        button.setTitle("Press", for: UIControlState.normal)
        button.setTitleColor(, for: UIControlState.normal)
        button.setTitleColor(UIColor.cyan, for: UIControlState.highlighted)
        button.addTarget(self, action: #selector(buttonPressed(sender:)), for: UIControlEvents.touchUpInside)
    func buttonPressed(sender: UIButton) {
        sender.setTitle("Pressed \(count)", for: UIControlState.normal)
        count = count+1
        print("button pressed!!")


UIButton - Selector Warning (Update with Swift 3.1)

No comments:

Post a Comment