Ad

In UIKit, How Do You Refactor Buttons From A ViewController?

I'm teaching my self UIKit and currently working on creating controls and other views programatically.

I've attempted to refactor buttons out of the ViewController and into their own views.

This is the tutorial I was following along, adapting it to my own project. And this is what I have:

ViewController.swift:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let buttonBar = ButtonBar(frame: CGRect(x: 0, y: 0, width: 400, height: 100), buttonAction: buttonWasPressed)
        view.addSubview(toolbar)

    }
    
    func buttonWasPressed() {
        print("Button Was Pressed")
    }
}

and the refactored button, ButtonBar.swift:

import UIKit

class ButtonBar: UIView {
    
    var buttonAction: (() -> Void)?
    
    init(frame: CGRect, buttonAction: @escaping() -> Void) {
        super.init(frame: frame)
        
        setup()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setup()
    }

    private func setup() {
        
        let buttonA = UIButton(type: .system)
        buttonA.setTitle("A", for: .normal)
        buttonA.frame = CGRect(x:20, y:20, width: 100, height: 100)
        buttonA.addTarget(self, action: #selector(self.buttonWasPressed), for: .touchUpInside)
        addSubview(buttonA)
        
        // more buttons to come...
        
    }
    
    @objc func buttonWasPressed() {
        buttonAction?()
    }
    
}

When the button is pressed, I expected the message "Button Was Pressed" to be printed from the ViewController, but that isn't happening. What did I do wrong?

My knowledge of UIKit, Swift, and iOS development is limited. Even after following along with the tutorial above, I still don't fully understand how this code is supposed to work.

And finally, is this the correct approach to refactor a lot of buttons into a single view?

Thank you!

Ad

Answer

You have to store the function inside the class

like:

self.buttonAction = buttonAction

on ButtonBar init

Ad
source: stackoverflow.com
Ad