Swift:获取特定类型的所有子视图并添加到数组中 [英] Swift: Get all subviews of a specific type and add to an array

查看:113
本文介绍了Swift:获取特定类型的所有子视图并添加到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 UIView 中有一个自定义按钮类,我想将其添加到数组中,以便可以轻松访问它们.有没有办法在 Swift 中获取特定类的所有子视图并将其添加到数组中?

I have a custom class of buttons in a UIView that I'd like to add to an array so that they're easily accessible. Is there a way to get all subviews of a specific class and add it to an array in Swift?

推荐答案

使用 is 运算符的 filter 函数可以过滤特定类的项目.

The filter function using the is operator can filter items of a specific class.

let myViews = view.subviews.filter{$0 is MyButtonClass}

MyButtonClass 是要过滤的自定义类.

MyButtonClass is the custom class to be filtered for.

要过滤和投射视图到自定义类型,请使用compactMap

To filter and cast the view to the custom type use compactMap

let myViews = view.subviews.compactMap{$0 as? MyButtonClass}

这篇关于Swift:获取特定类型的所有子视图并添加到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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