-5

create login button( set title and conner Radius on UI button)

 lazy var loginButton: UIButton = {
    let button = UIButton()
    button.setTitle("Log In", for: .normal)
    button.layer.cornerRadius = 15
    button.backgroundColor = UIColor.red
 
    
    return button
}()
Chithian
  • 253
  • 3
  • 8
  • Does this answer your question? [How to add action for UIButton](https://stackoverflow.com/questions/8341543/how-to-add-action-for-uibutton) – lazarevzubov Aug 22 '22 at 05:12
  • "here is my way to just create uibutton only" Except that the code _you've_ shown wouldn't even compile. – matt Aug 23 '22 at 12:24

3 Answers3

1

The modern way is to add the action as a UIAction.

lazy var test: UIButton = {
    let test = UIButton()
    test.translatesAutoresizingMaskIntoConstraints = false
    test.setTitle("See More Answers", for: .normal)
    test.setTitleColor(.systemBlue, for: .normal)
    let action = UIAction { action in
        print("howdy!")
    }
    test.addAction(action, for: .touchUpInside)
    return test
}()

Nicer syntax can be achieved through an extension, as I demonstrate here.

matt
  • 515,959
  • 87
  • 875
  • 1,141
-2
@objc func buttonAction() {
    print("Button Tapped")
}

test.addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside)
JJHA
  • 76
  • 7
-2

I have given the example for create the custom button and the custom label and set constraint in coding. The below code also contains the programmatically button action.

import UIKit

class ViewController: UIViewController {
    let button = UIButton(frame: CGRect(x: 100,y: 400,width: 200,height: 60))
    var label = UILabel(frame: CGRect(x: 100, y: 200, width: 200, height: 60))
    var count : Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        
        button.setTitle("Click Button",for: .normal)
        button.backgroundColor = UIColor.blue
        button.setTitleColor(.white, for: .normal)
        button.addTarget(self,action: #selector(buttonAction),for: .touchUpInside)
        
        label.font = .systemFont(ofSize: 50)
        label.backgroundColor = UIColor.gray
        label.textAlignment = .center
        
        self.view.addSubview(button)
        self.view.addSubview(label)
    }

    @objc
    func buttonAction() {
        self.count += 1
        self.label.text = "\(count)"
    }
    
}

Output :-

Value of label increases when the button is click.

enter image description here

Saurabh Pathak
  • 879
  • 7
  • 10