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?
相关问题
- What uses more memory in c++? An 2 ints or 2 funct
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- State preservation and restoration strategies with
- How to get the maximum of more than 2 numbers in V
相关文章
- 现在使用swift开发ios应用好还是swift?
- Numpy matrix of coordinates
- UITableView dragging distance with UIRefreshContro
- Using if let syntax in switch statement
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
I can't test it right now but this should work in Swift 2:
Which returns an array of
YourView
Here's a tested, typical example, to get a count:
The
filter
function using theis
operator can filter items of a specific class.MyButtonClass
is the custom class to be filtered for.For this case, I think we could use Swift's
first.where
syntax, which is more efficient thanfilter.count
,filter.isEmpty
.Because when we use
filter
, it will create a underlying array, thus not effective, imagine we have a large collection.So just check if a view's
subViews
collection contains a specific kind of class, we can use thiswhich equivalent to: find me the first match to BannerView class in this view's subViews collection. So if this is true, we can carry out our further logic.
Reference: https://github.com/realm/SwiftLint/blob/master/Rules.md#first-where
From Swift 4.1, you can use new compactMap (flatMap is now depcrecated): https://developer.apple.com/documentation/swift/sequence/2950916-compactmap (see examples inside)
In your case, you can use:
And you can execute actions to all buttons using map:
To do this recursively (I.e. fetching all subview's views aswell), you can use this generic function:
To fetch all UILabel's in a view hierarchy, just do this:
If you want to update/access those specific subviews then use this,