问题
I'm trying to remove all the subviews that I've added to my view, so I've implemented a loop to iterate over the subviews with the following:
for subview in view.subviews {
println(subview)
//subview.removeFromSuperview()
}
I tested this by adding a UILabel to my view and then ran this code. The output contained my UILabel but also a _UILayoutGuide. So, my question is how can I determine if a subview is one that I added or one that the system added?
回答1:
If you just want to prevent the loop from removing the _UILayoutGuide
(which is of class UILayoutSupport
), try this:
for subview in self.view.subviews {
if !(subview is UILayoutSupport) {
print(subview)
subview.removeFromSuperview()
}
}
And generally speaking, if you'd like to prevent the removal of views other than the _UILayoutGuide
and if you know the specific types of subviews you'd like to remove from your UIView, you can limit the subviews you remove to those types, ex:
for subview in view.subviews {
if subview is ULabel {
println(subview)
subview.removeFromSuperview()
}
}
回答2:
One option is to give all the views you add a specific tag. Then only remove them if they have that tag.
userCreatedView.tag = 100;
...
for subview in view.subviews {
if (subview.tag == 100) {
subview.removeFromSuperview()
}
}
You could also keep an Array of all the subviews that the user has added then check to see if that subview is in your userAddedViewsArray
Or you could create a subclass of UIView for your user added views and then only remove the subviews that are that class
回答3:
i solve problem like this way.... first i added sub view
- [self.view addSubview:genderPicker];
then remove only that subview from the view
- [genderPicker removeFromSuperview];
回答4:
indicator on off by string input fun swift 2.2 and above
func activityonoff(viewcontroler:UIViewController,string:String){
let container: UIView = UIView()
let loadingView: UIView = UIView()
if string == "on"{
container.frame = viewcontroler.view.frame
container.center = viewcontroler.view.center
container.backgroundColor = UIColor.whiteColor()
container.alpha = 1
container.tag = 1
loadingView.frame = CGRectMake(0, 0, 80, 80)
loadingView.center = container.center
loadingView.backgroundColor = UIColor(red: 4/255, green: 68/255, blue: 68/255, alpha: 0.7)
loadingView.clipsToBounds = true
loadingView.layer.cornerRadius = 10
let actInd: UIActivityIndicatorView = UIActivityIndicatorView()
actInd.frame = CGRectMake(0.0, 0.0, 40.0, 40.0);
actInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
actInd.center = CGPointMake(loadingView.frame.size.width / 2,loadingView.frame.size.height / 2);
loadingView.addSubview(actInd)
container.addSubview(loadingView)
viewcontroler.view.addSubview(container)
actInd.startAnimating()
}
else{
for v in viewcontroler.view.subviews{
if v.tag == 1{
v.removeFromSuperview()
}
}
}
}
来源:https://stackoverflow.com/questions/27237457/how-to-remove-only-user-added-subviews-from-my-uiview