如何在初始化后更新自定义类中的UILabel文本(Swift 3)

时间:2017-04-01 13:52:39

标签: ios swift swift3 storyboard initialization

我有自定义UIStackView类,但在初始化后我无法更改其中的标签,因为它引用了不同的标签对象。

//  ViewBlocksController.swift
//  player

import UIKit

let nowPlayingControl = NowPlayingController()

@IBDesignable class TitlesFrame: UIStackView {
    //Labels variables
    let songTitle = UILabel()
    let artistAlbumTitle = UILabel()

    //Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        arrangeView()
    }

    required init(coder: NSCoder) {
        super.init(coder: coder)
        arrangeView()
    }

    func arrangeView(){
        //Get initial text
        (songTitle.text, artistAlbumTitle.text) = nowPlayingControl.getTitles()

        //Add labels to the stack
        addArrangedSubview(artistAlbumTitle)
        addArrangedSubview(songTitle)

        //Test what label is used
        print(songTitle)
    }

    func updateTitles(){
        (songTitle.text, artistAlbumTitle.text) = nowPlayingControl.getTitles()
    }
}

我从MainViewController类调用updateTitles():

//  MainViewController.swift
//  player

import UIKit

class MainViewController: UIViewController {

    let titlesFrame = TitlesFrame()

    //Will call this on custom notification
    func callUpdate(){
        titlesFrame.updateTitles()
    }
}

打印为我提供了以下对象:

<**UILabel: 0x100c15b90**; frame = (0 0; 0 0); text = 'Unknown Artist
\342\200— Unknown ...'; userInteractionEnabled = NO; layer =
<_UILabelLayer: 0x1700956d0>>

<**UILabel: 0x100d19d90**; frame = (0 0; 0 0); text = 'Unknown Artist —
Unknown ...'; userInteractionEnabled = NO; layer = <_UILabelLayer:
0x174097f70>>

当我尝试使用updateTitles()方法更新标签时,它总是更新第一个对象(UILabel:0x100c15b90)。但是,Storyboard会显示第二个对象(UILabel:0x100d19d90)并且它永远不会更新。

如何在Storyboard上更新标签?

1 个答案:

答案 0 :(得分:0)

感谢@OOPer我发现我的问题不在于初始化程序,而在于我如何引用我的自定义类。

要更新Storyboard上的标签,我在MainViewController类中用let titlesFrame = TitlesFrame()替换了@IBOutlet var titlesFrame: TitlesFrame!。 IBOutlet连接到Storyboard上继承的UIStackView对象:

//  MainViewController.swift
//  player

import UIKit

class MainViewController: UIViewController {

    //IBOutlet is connected to the UIStackView object on the Storyboard
    @IBOutlet weak var titlesFrame: TitlesFrame!

    //Will call this on custom notification
    func callUpdate(){
        titlesFrame.updateTitles()
    }
}