繁体   English   中英

Swift:UIlabel 文本属性已更改,但 UI 中的显示值未更改

[英]Swift: UIlabel text property gets changed but the displayed value in the UI doesn't change

当用户单击集合视图项时,我想更改 UILabelView 文本属性:

// This is another viewController not the one containing the label
// Handle collectionViewItem selection
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print("INSIDE TableViewCell2.collectionView 3")
    TabsBarController.sharedInstance.testTitle = "UILabelText"
    print("didSelectItem\(indexPath)")
}

设置后,我尝试在此处更新它:

  class TabsBarController: UIViewController {
    static let sharedInstance = TabsBarController()
    var movieTitle:  UILabel? = UILabel(frame: CGRect(x: 0, y: 0, width: 300.00, height: 30.00));
    var testTitle: String? = nil {
        didSet {
            print("testTitle.didSet: ",testTitle!) // logs the correct text
            movieTitle?.text = testTitle
            print(" movieTitle?.text : ", movieTitle?.text ) // logs the correct text
        }
    }
}

这里的问题是,即使movieTitle?.text在 UI 中, movieTitle UILabel也不会改变。 我已经阅读了许多类似问题的答案,并且所有答案都指向使用主线程,因此我添加了以下内容:

 class TabsBarController: UIViewController {
        static let sharedInstance = TabsBarController()
        var movieTitle:  UILabel? = UILabel(frame: CGRect(x: 0, y: 0, width: 300.00, height: 30.00));
        var testTitle: String? = nil {
            didSet {
                // I added this but still nothing changed.
                DispatchQueue.main.async {
                    // Run UI Updates
                    print("testTitle.didSet: ",testTitle!) // logs the correct text
                    movieTitle?.text = testTitle
                    print(" movieTitle?.text : ", movieTitle?.text ) // logs the correct text
                }
                
            }
        }
    }

但是,UI 仍然没有更新。 知道为什么会发生这种情况以及如何解决吗?

注意:这是层次结构:
层次结构是这样的 TabsBarViewController-> MoviesViewController -> UITableView->UitableViewCell->CollectionView

根据项目层次结构,我必须按照此处的说明操作,以便能够从tableViewCell内部访问UITabsBarController testTitle属性。 只是一个警告,我必须做这个演员:

 // Handle collectionViewItem selection
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("INSIDE TableViewCell2.collectionView 3")
   
          if let vc2 =  self.viewController?.parent as? TabsBarController {
             vc2.testTitle = "THIS WILL DEFINITELY ABSOLUTELY WORK I DONT CARE"
        }
        print("didSelectItem\(indexPath)")
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM