使用UISlider抛出UILabel"未解析的标识符"发件人呼叫错误

时间:2018-05-06 18:41:25

标签: swift uilabel uislider

以下代码是我使用的唯一代码。我已经以编程方式构建了一个带有我想要更新的标签的UISlider。我编写了一个函数,应该调用UISlider的发送者并将标签字段更新为滑块的值。但它不断抛出未解决的标识符"标签的变量名称的错误。我在哪里放置功能,以便它可以访问标签值?我已经尝试了一切。

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad()
    {
        super.viewDidLoad()
        let mySlider = UISlider(frame:CGRect(x: 60, y:550, width: 300, height: 20))
        mySlider.minimumValue = 5
        mySlider.maximumValue = 60
        mySlider.isContinuous = true
        mySlider.tintColor = .white
        mySlider.addTarget(self, action: #selector(ViewController.sliderValueDidChange(_:)), for: .valueChanged)

        let minuteLabel = UILabel(frame: CGRect(1500, 2000, 150, 1200))
        minuteLabel.center = CGPoint(200, 350)
        minuteLabel.textAlignment = .center
        minuteLabel.font = UIFont(name: minuteLabel.font.fontName, size:250)
        mySlider.addTarget(self, action: #selector(ViewController.sliderValueDidChange(_:)),for: .valueChanged)
        minuteLabel.textColor = UIColor.white
        minuteLabel.text = "\(mySlider.value)"

        self.view.addSubview(minuteLabel)
        self.view.addSubview(mySlider)
    }

    public func sliderValueDidChange(_sender: UISlider) {
        minuteLabel.text = "\(_sender.value)"
    }
}

1 个答案:

答案 0 :(得分:1)

这是因为您在minuteLabel中创建viewDidLoad()但未分配到ViewController内的任何媒体资源。

您可以在课堂内创建属性minuteLabel,并将minuteLabelviewDidLoad()分配给此。

class ViewController: UIViewController {

    private var minuteLabel: UILabel?

    override func viewDidLoad()
    {
        super.viewDidLoad()
        let mySlider = UISlider(frame:CGRect(x: 60, y:550, width: 300, height: 20))
        mySlider.minimumValue = 5
        mySlider.maximumValue = 60
        mySlider.isContinuous = true
        mySlider.tintColor = .white
        mySlider.addTarget(self, action: #selector(ViewController.sliderValueDidChange(_:)), for: .valueChanged)

        let minuteLabel = UILabel(frame: CGRect(1500, 2000, 150, 1200))
        minuteLabel.center = CGPoint(200, 350)
        minuteLabel.textAlignment = .center
        minuteLabel.font = UIFont(name: minuteLabel.font.fontName, size:250)
        mySlider.addTarget(self, action: #selector(ViewController.sliderValueDidChange(_:)),for: .valueChanged)
        minuteLabel.textColor = UIColor.white
        minuteLabel.text = "\(mySlider.value)"

        self.view.addSubview(minuteLabel)
        self.view.addSubview(mySlider)

        self.minuteLabel = minuteLabel // assign to class property
    }

    public func sliderValueDidChange(_sender: UISlider) {
        minuteLabel?.text = "\(_sender.value)"
    }

}