Swift-检索子视图 [英] Swift - Retrieving subviews

查看:131
本文介绍了Swift-检索子视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我正在向视图中添加标签,然后在单击按钮时尝试从视图中清除特定标签,并且在尝试检索子视图时遇到错误:

In my application I am adding labels to the view and then I am attempting to clear particular labels from the view when a button is clicked and am running into an error when trying to retrieve the subviews:

class FirstViewController: UIViewController {

     @IBAction func btnAddTask_Click(sender: UIButton){

          var subViews = self.subviews.copy()

    }
 }

我得到了错误:

"FirstViewController"没有名为"subviews"的成员

'FirstViewController' does not have a member named 'subviews'

如何获取当前视图的子视图?

How can I get the subviews of the current view?

推荐答案

UIViewController没有subviews属性.它具有view属性,而该属性具有subviews属性:

UIViewController doesn't have a subviews property. It has a view property, which has a subviews property:

for subview in self.view.subviews {
   // Manipulate the view
}

但是通常这不是一个好主意.您应该将所需的标签放入IBOutletCollection中并对其进行迭代.否则,您将完全依赖于子视图的确切集合(可能会更改).

But typically this is not a good idea. You should instead put the labels you want into an IBOutletCollection and iterate over that. Otherwise you've very tied to the exact set of subviews (which may change).

要创建IBOutletCollection,请在IB中选择所需的所有标签,然后将其拖动到源代码中.它应该询问您是否要创建一个集合数组. (请注意,此数组的顺序没有保证.)

To create the IBOutletCollection, select all the labels you want in IB, and control-drag them to the source code. It should ask if you want to make a collection array. (Note that there is no promise on the order of this array.)

这篇关于Swift-检索子视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆