Search code examples
iosswiftuiviewuibuttonaddtarget

Swift class with uibutton.addTarget to UIView not working


I created a new file with the following class:

import Foundation
import UIKit

var Feld = classFeld()

class classFeld {

     let button = UIButton()

     func createButton() -> UIButton {
         button.frame = CGRect(x: 10, y: 50, width: 200, height: 100)
         button.backgroundColor=UIColor.black
         button.addTarget(self, action: #selector(ButtonPressed(sender:)), for: .touchUpInside)
        return button
    }

    @objc func ButtonPressed(sender: UIButton!) {
        button.backgroundColor=UIColor.red
    }
}

And this is my ViewController:

import UIKit

class ViewController: UIViewController {

   override func viewDidLoad() {
        super.viewDidLoad()
        mainview.addSubview(Feld.createButton())
        self.view.addSubview(mainview)
    }

    var  mainview=UIView()
}

When I start the app a black button is created but when I click on it it doesnt color red. If I add the button instead of

mainview.addSubview(Feld.createButton())

to

self.view.addSubview(Feld.createButton())

it works and the button turns red.

May I anyone explain me why? It should make no difference if I add something to self.view or to a subview which is then added to self.view?


Solution

  • Because you need to give it a frame and add it to self.view

    var mainview = UIView()