尝试将文本分配给标签时出现预期声明错误



>我正在尝试创建一个包含其他标签的标签分类。

这是我的代码

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!(。

有几种方法可以创建可重用的 UI 元素,该元素由 2 个UILabel组成,可以通过编程方式创建。您可以对UIStackView进行子类化以自动处理布局,或者如果您想要更多控制,您可以简单地子类化UIView,将 2 个UILabels添加为subViews,并通过以编程方式添加自动布局约束来处理布局。

下面是使用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"

最新更新