首页 > 解决方案 > 尝试将文本分配给标签时出现预期的声明错误

问题描述

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

这是我的代码

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()
    }
}

标签: iosswift

解决方案


您的代码有几个问题。您收到的错误是因为您只能在类范围内声明变量或函数,并且top.text您试图在函数范围外修改类的实例属性,这是不允许的。

其次,你不应该在一个很少有意义的函数中声明一个类。

UILabel!最后,如果您要立即为其赋值,请不要将任何内容声明为隐式展开的可选项 ( )。

有几种方法可以创建由 2 个组成的可重用 UI 元素,UILabel并且可以通过编程方式创建。您可以将 a 子类UIStackView化以自动处理布局,或者如果您想要更多控制,您可以简单地子类UIView化,将 2 添加UILabelsubViews 并通过以编程方式添加 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"

推荐阅读