首页 > 解决方案 > 从父类继承的子类不改变颜色

问题描述

我的快速代码试图将 view1 从父类 1 继承到子类 2。view1 被重新识别,但是当代码运行并应用 segue 时,屏幕上没有任何变化。view1 应该将颜色从粉红色变为青色。不是我不明白为什么没有应用更改。

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

        
    }

}

标签: swiftinheritancesegueparent-child

解决方案


您的代码运行良好;二的介绍正在发生。但是你什么也看不到,因为:

  • The backgroundColorof Two'sviewnil, ie .clear,所以你看不到背景。

  • 在二中,您永远不会在界面中放入任何东西。您与 中的按钮交谈view1viewDidLoad但与 One 不同的是viewDidLoad,您从未将该按钮放入界面中。所以你看不到按钮(因为它不存在)。

一个最小的“修复”是调用superTwo's viewDidLoad

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

推荐阅读