简体   繁体   English

如何从父UIStackView引用和修改子视图UILabel

[英]How to reference and modify subview UILabel from parent UIStackView

I have a UIStackView object to which I have added a UILabel as the first subview. 我有一个UIStackView对象,向其中添加了UILabel作为第一个子视图。 Here is what my code looks like: 这是我的代码:

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

Now, I wish to obtain a reference to the displayLabel object later on so I can modify it's text field. 现在,我希望稍后获得对displayLabel对象的引用,以便可以修改它的文本字段。 The only way I could do this was somewhat of a hack: 我能做到这一点的唯一方法有点像破解:

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

Is there a better way to do this ? 有一个更好的方法吗 ?

If displayLabel should be not instance variable, then setting a tag value for it might be useful: 如果displayLabel应该是没有实例变量,然后设置一个标记值可能是有用的:

An integer that you can use to identify view objects in your application. 可用于标识应用程序中的视图对象的整数。

What you can do: 你可以做什么:

// declaring a global constant for holding the label tag value
let displayLabelTageValue = 101

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

And for getting identified displayLabel label: 并获得displayLabel标签:

if let displayLabel = view.viewWithTag(displayLabelTageValue) as? UILabel {
    // displayLabel is wanted label!
} else {
    // make sure that the tag value is matched
}

Store a reference to the label in a property: 将对标签的引用存储在属性中:

var displayLabel: UILabel?

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

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

It depends on what your goals are. 这取决于您的目标。

If you want to set the text of the view in position 0 of your stack view to a specific string, the code you posted is the right way to go. 如果要将堆栈视图位置0的视图文本设置为特定字符串,则发布代码是正确的方法。

If you have a label that you want to be able to change regardless of it's position in the stack view then you should save a reference to it in an instance variable of your view controller, and then you can set it's text to a new string at any time. 如果您有一个标签,无论标签在堆栈视图中的位置如何,都可以对其进行更改,则应将其引用保存在视图控制器的实例变量中,然后可以将其文本设置为新的字符串,网址为任何时候。

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

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