ios - 尝试将文本分配给标签时出现预期的声明错误
问题描述
我正在尝试创建一个包含其他标签的标签类。
这是我的代码
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
class mainLabel: UILabel{
var top: UILabel! = UILabel()
top.text = "text" //*Expected declaration error
var down: UILabel! = UILabel()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
解决方案
您的代码有几个问题。您收到的错误是因为您只能在类范围内声明变量或函数,并且top.text
您试图在函数范围外修改类的实例属性,这是不允许的。
其次,你不应该在一个很少有意义的函数中声明一个类。
UILabel!
最后,如果您要立即为其赋值,请不要将任何内容声明为隐式展开的可选项 ( )。
有几种方法可以创建由 2 个组成的可重用 UI 元素,UILabel
并且可以通过编程方式创建。您可以将 a 子类UIStackView
化以自动处理布局,或者如果您想要更多控制,您可以简单地子类UIView
化,将 2 添加UILabel
为subView
s 并通过以编程方式添加 Autolayout 约束来处理布局。
这是使用UIStackView
子类的解决方案。修改任何属性以满足您的确切需求,这仅用于演示。
class MainLabel: UIStackView {
let topLabel = UILabel()
let bottomLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
axis = .vertical
distribution = .fillEqually
addArrangedSubview(topLabel)
addArrangedSubview(bottomLabel)
topLabel.textColor = .orange
topLabel.backgroundColor = .white
bottomLabel.textColor = .orange
bottomLabel.backgroundColor = .white
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
在操场上测试:
PlaygroundPage.current.needsIndefiniteExecution = true
let mainLabel = MainLabel(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
PlaygroundPage.current.liveView = mainLabel
mainLabel.topLabel.text = "Top"
mainLabel.bottomLabel.text = "Bottom"
推荐阅读
- pine-script - Pinescript:如何将每周高点和低点更改为之前的每周高点和低点
- c# - 在 asp.net core 中首次运行时向表中添加一些数据(填充数据库)
- excel - VBA 从以 Workbook 命名的工作表创建 CSV
- javascript - 如何在 VueJS 项目中使用leaflet-semicircle 和 vue2-leaflet?
- java - 使用 OpenNTF POI 从 Excel 获取值,但 row.getCellType() 不再工作
- anylogic - 从数据库导入的模型开始时间
- batch-file - 批处理文件检查程序打开的文件
- android - 如何在 android 设备上获取应用程序崩溃详细信息(自己的统一应用程序)
- javascript - 使用 $obj->select 对从数据库中提取的数组进行排序
- python - WSGI 文件未在 Windows Server 2012 上的 Apache 2.4 上加载 Python Flask 文件