add a button that submits in swift

To add a button that submits in Swift, you can use the UIButton class which inherits from UIControl.

main.swift
let submitButton = UIButton(type: UIButtonType.system)
submitButton.setTitle("Submit", for: .normal)
submitButton.addTarget(self, action: #selector(submitButtonTapped), for: .touchUpInside)
view.addSubview(submitButton)
220 chars
5 lines

In the code above, we create a button of type system with the title "Submit". We then add a target to the button that will execute an action when the button is tapped. In this case, we're calling a function called submitButtonTapped.

To actually handle the button tap, you need to define the submitButtonTapped function:

main.swift
@objc func submitButtonTapped() {
    // Submit button has been tapped
    // Add your code here to handle the submission
}
124 chars
5 lines

In this function, you can add code to handle the submission. Note that we prefix the function with @objc annotation, which is required when adding targets from UIButton objects.

With these two pieces of code, you should now have a button that submits in your iOS Swift application.

gistlibby LogSnag