Swift:UIlabel 文本属性被更改,但 UI 中显示的值不会改变



当用户单击集合视图项时,我想更改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中,movieTitleUILabel也不会改变。我读过很多类似问题的答案,所有答案都指向使用主线程,所以我添加了以下内容:

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
}

}
}
}

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

注意:这是层次结构:
层次结构如下TabsBarViewController->电影ViewController->UITableView->UitableViewCell->集合查看

基于项目层次结构,为了能够从tableViewCell内部访问UITabsBarControllertestTitle属性,我必须遵循此处的说明。只有一个警告,我必须做这个铸造:

// 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)")
}

最新更新