Search code examples
swiftbuttonswift4

Buttons Programmatically on Swift 4


A quick question, I am trying to create a function called setupHeader() in which when called, setups up all the views and buttons of the header. The problem is with the Log Out button, for some reason I cannot get it right.

The first error is that the addTarget of the button doesn't recognize "self". Any suggestions?

The second one is that the #selector only works with the @objc func and the function cannot be in the main setupHeader function. Where should I put it? here is a snippet of my code:

import Foundation
import UIKit

func setupHeader(vc: UIViewController) {

let headerFiller: UIView = {
    let view = UIView()
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = supaGray
    return view
}()

let header: UIView = {
    let view = UIView()
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = supaGray
    return view
}()

let logOutButton: UIButton = {
    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitle("Log Out", for: .normal)
    button.setTitleColor(.blue, for: .normal)
    button.titleLabel?.adjustsFontSizeToFitWidth = true
    button.titleLabel?.textAlignment = .left
    button.addTarget(self, action: #selector(handleLogOutButton), for: .touchUpInside)
    return button
}()

func handleLogOutButton() {

}

vc.view.addSubview(header)
header.topAnchor.constraint(equalTo: vc.view.safeAreaLayoutGuide.topAnchor).isActive = true
header.leftAnchor.constraint(equalTo: vc.view.leftAnchor).isActive = true
header.rightAnchor.constraint(equalTo: vc.view.rightAnchor).isActive = true
header.heightAnchor.constraint(equalToConstant: 40).isActive = true

header.addSubview(logOutButton)
logOutButton.centerYAnchor.constraint(equalTo: header.centerYAnchor, constant: -5).isActive = true
logOutButton.leftAnchor.constraint(equalTo: header.leftAnchor, constant: 7).isActive = true
logOutButton.widthAnchor.constraint(equalTo: header.widthAnchor, multiplier: 0.17).isActive = true
logOutButton.heightAnchor.constraint(equalToConstant: 40).isActive = true

vc.view.addSubview(headerFiller)
headerFiller.topAnchor.constraint(equalTo: vc.view.topAnchor).isActive = true
headerFiller.leftAnchor.constraint(equalTo: vc.view.leftAnchor).isActive = true
headerFiller.rightAnchor.constraint(equalTo: vc.view.rightAnchor).isActive = true
headerFiller.bottomAnchor.constraint(equalTo: header.topAnchor).isActive = true
}

Solution

  • Declare your button press callback this way.

    @objc func handleLogOutButton() {
    
    }
    

    And For self error use vc as your passing as argument above in function.