ios - 如何从父 UIStackView 引用和修改 subview UILabel

标签 ios swift

我有一个 UIStackView 对象,我在其中添加了一个 UILabel 作为第一个 subview 。这是我的代码的样子:

func createStackView() -> UIStackView? {
  var displayLabel = UILabel()
  // Set properties of displayLabel
  ...
  let myStackView = UIStackView(arrangedSubviews: [displayLabel, stackViewRow1, stackViewRow2]
  return myStackView
}

现在,我希望稍后获得对 displayLabel 对象的引用,以便我可以修改它的文本字段。 我能做到这一点的唯一方法有点像 hack:

var displayPanel = topStackView.arrangedSubviews[0]
if let displayLabel = displayPanel as? UILabel {
      displayLabel.text = "Ready"
}

有更好的方法吗?

最佳答案

在属性中存储对标签的引用:

var displayLabel: UILabel?

// then when you create the stack view
self.displayLabel = displayLabel

// to access it later
if let displayLabel = displayLabel {
    displayLabel.text = "Ready"
}

关于ios - 如何从父 UIStackView 引用和修改 subview UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42892770/

相关文章:

ios - iOS 版本 13 中的照片库插件崩溃

ios - 如何在两个表格 View 单元格之间添加一个按钮

swift - Switch 语句中 Case 的顺序对 Swift 中的执行速度有影响吗?

swift - 串行 Grand Central Dispatch 中的完成处理程序

ios - 当我改变它的坐标时,自定义 MKAnnotation 消失

ios - 在 iOS5.1/6 中,presentViewController 和 viewDidAppear 没有被调用

ios - StageWebView、iOS、本地文件

iphone - 更改 ABRecordRef 属性

ios - SpriteKit : run action while scene is paused

arrays - 如何从字典数组中获取字典索引?