1

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?

Andy
  • 185
  • 1
  • 13

3 Answers3

2

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

var mainview = UIView()
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • Adding a frame works! Thanks a lot. I dont understand though why the button is displayed (black) without a frame. And addTarget (turning red) is not displayed without a frame. – Andy Jul 17 '18 at 09:00
  • This always happens with frames , actually the mainView had a zero default frame , but if you set **mainview.clipsToBounds = true** the button won't show – Shehata Gamal Jul 17 '18 at 09:06
1

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())
    }        
}
Sharad Chauhan
  • 4,821
  • 2
  • 25
  • 50
1

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)

    }
}
Moayad Al kouz
  • 1,342
  • 1
  • 9
  • 19