Disable UIButton Example in Swift

In this Swift code example, you will learn how to disable UIButton. The quickest way to disable the button in Swift is to simply set the button’s isEnabled property to false. For example button.isEnabled = false. 

Below is a complete code example in Swift that demonstrates how to:

  • Create new UIButton,
  • Position button within a view,
  • Set UIButton title,
  • Set UIButton background color,
  • Set button tint color,
  • Add button target function,
  • Disable UIButton,
  • Add UIButton to a UIView as a subview.

Code Example

import UIKit
class ViewController: UIViewController  {
    override func viewDidLoad() {
    override func viewWillAppear(_ animated: Bool) {
        // Instantiate UIButton
        let button = UIButton(type: UIButton.ButtonType.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: UIControl.State.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(self.buttonAction(_:)), for: .touchUpInside)
        // Disable button
        button.isEnabled = false
        // Add UIButton to a UIView as subview
    @objc func buttonAction(_ sender:UIButton!)
        print("Button tapped")

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.

Leave a Reply

Your email address will not be published. Required fields are marked *