Warm tip: This article is reproduced from serverfault.com, please click

child class inheriting from parent class not changing color

发布于 2020-11-27 22:22:38

My swift code is trying to inherit view1 from parent class one to child class two. view1 is recongizined but when the code is run and the segue is applied nothing changes on the screen. view1 should change colors from pink to cyan. Its not I don't understand why the change is not being applied.

import UIKit

class one : UIViewController {
 
    
  var view1 = UIButton()
 
    

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        [view1].forEach{
            $0.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview($0)
        }
        
        
        view1.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
      
        
        view1.backgroundColor = .systemPink
     

        view.backgroundColor = .orange
        
        view1.addTarget(self, action: #selector(move), for: .touchDown)

    }
        
    
    @objc func move(){
        let vc = two()
        vc.modalPresentationStyle = .overCurrentContext // actually .fullScreen would be better
        self.present(vc, animated: true)
    }



}


class two: one {
    
    
    override func viewDidLoad() {
        
        
        view1.backgroundColor = .cyan

        
    }

}
Questioner
joe buck
Viewed
0
matt 2020-11-28 07:39:04

Your code is working fine; the presentation of Two is happening. But you don't see anything, because:

  • The backgroundColor of Two's view is nil, i.e. .clear, so you don't see the background.

  • In Two, you never put anything into the interface. You talk to the button view1 in viewDidLoad, but unlike One's viewDidLoad, you never put that button into the interface. So you don't see the button (because it isn't there).

A minimal "fix" would be to call super in Two's viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad() // *
    view1.backgroundColor = .cyan
}