简体   繁体   中英

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?

因为您需要给它一个框架并将其添加到self.view

var mainview = UIView()

This is because you are just initializing a UIView without giving it any frame and adding it to the main view.

You need to give frame to your mainview also. For example :

class ViewController: UIViewController {
   var mainview = UIView()
   override func viewDidLoad() {
        super.viewDidLoad()
        mainview.frame = CGRect(x: 10, y: 50, width: 300, height: 300)
        self.view.addSubview(mainview)
        mainview.addSubview(Feld.createButton())
    }        
}

Here is changes on ViewController class and working fine:

class ViewController: UIViewController {
    var  mainview: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        mainview = UIView(frame: self.view.bounds)
        mainview.addSubview(Feld.createButton())
        self.view.addSubview(mainview)

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM