Disable UIButton Example in Swift

In this Swift code example we will learn how to disable UIButton.

  • Create new UIButton
  • Position button within a view
  • Set UIButton title
  • Set UIButton background colour
  • Set button tint colour
  • Add button target function
  • Disable UIButton
  • Add UIButton to a UIView as subview
import UIKit

class ViewController: UIViewController  {
    override func viewDidLoad() {
    override func viewWillAppear(_ animated: Bool) {
        // Instantiate UIButton
        let button = UIButton(type: UIButtonType.system) as UIButton
        let xPostion:CGFloat = 50
        let yPostion:CGFloat = 100
        let buttonWidth:CGFloat = 150
        let buttonHeight:CGFloat = 45
        // Position button within a view
        button.frame = CGRect(x: xPostion, y: yPostion, width: buttonWidth, height: buttonHeight)
        // Set UIButton title
        button.setTitle("Tap me", for: UIControlState.normal)
        //Set UIButton background colour
        button.backgroundColor = UIColor.blue
        // Set button tint colour
        button.tintColor = UIColor.white
        // Add button target function
        button.addTarget(self, action: #selector(ViewController.buttonAction(_:)), for: .touchUpInside)
        // Disable button
        button.isEnabled = false
        // Add UIButton to a UIView as subview
    func buttonAction(_ sender:UIButton!)
        print("Button tapped")

Learn iOS Development with these Video Courses

How to Make a Freaking iPhone App - iOS 10 and Swift 3
icon icon

iOS 10 & Swift 3: From Beginner to Paid Professional

The Complete iOS 10 Developer Course - Build 21 Apps

Swift 3 - Learn to Code with Apple's New Language
icon icon

Learn How to Build Mobile Apps for iOS with Swift, PHP and MySQL
icon icon

Follow me on one of your favourite social networks to learn about new video tutorials and code examples:

Twitter: @SwiftVideoBlog
Google Plus: https://plus.google.com/+SergeyKargopolov/posts
Facebook: Swift Developer Blog on Facebook