In Objective-C I'm using this code to remove any sub-views:
[self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
But how to use it in swift? I saw apple documentation to use that method in swift
func makeObjectsPerformSelector(_ aSelector: Selector)
but when I try it, I get an error: 'AnyObject[]' does not have a member named 'makeObjectsPerformSelector'
Are there any ways to remove sub-views in swift?
Use forEach
:
self.view.subviews.forEach { subview in
subview.removeFromSuperview()
}
Or like this:
view.subviews.forEach { $0.removeFromSuperview() }
It only works on NSArray and NSMutableArray objects.
This will work:
let ar: NSArray = [obj1, obj2, obj3]
ar.makeObjectsPerformSelector("someSelector")
Note that if you have an Array<AnyObject>
you can freely convert to NSArray
and vise versa.
let anNSArray: NSArray = anArrayOfAnyObject
anNSArray.makeObjectsPerformSelector( "someSelector")
As of Xcode 7, the full family of performSelector methods are available in Swift, including makeObjectsPerformSelector()
for NSArray
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With