swift - 从父类继承的子类不改变颜色
问题描述
我的快速代码试图将 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
}
}
解决方案
您的代码运行良好;二的介绍正在发生。但是你什么也看不到,因为:
The
backgroundColor
of Two'sview
是nil
, ie.clear
,所以你看不到背景。在二中,您永远不会在界面中放入任何东西。您与 中的按钮交谈
view1
,viewDidLoad
但与 One 不同的是viewDidLoad
,您从未将该按钮放入界面中。所以你看不到按钮(因为它不存在)。
一个最小的“修复”是调用super
Two's viewDidLoad
:
override func viewDidLoad() {
super.viewDidLoad() // *
view1.backgroundColor = .cyan
}
推荐阅读
- python - 任何想法如何从给定的点云中分割出盒子表面?
- google-cloud-platform - 关于烫发安装问题的 Google OCR
- scala - 我想反序列化 scala 中的 json 对象
- python - 有没有办法从 2D (x,y) 数据集中绘制同心圆颜色图,其中 x 是 python 中的圆的半径
- php - Symfony 5 在某些请求中没有检测到正确的语言环境
- excel-formula - 如何在 Excel 的行项目中添加“上次更新日期”?
- jmeter - Jmeter 读取 CSV 文件返回
写在上面之后 - dns - Name.com 裸域到 www
- php - Tenancy - 无法声明类 CreateUsersTable,因为该名称已在使用中
- reactjs - Next.js / React 单页应用程序需要每个项目的 url