Removing Subzones from ScrollView Swift

I use for-loop to create labels and buttons inside my scrollView. Is it possible to delete all objects that are outside of my scrollView? (I would like to update it with new content)

for peop in personArray{ scrollView.clearContent ?????? // Name label var label: UILabel = UILabel() label.frame = CGRectMake(8, CGFloat(nameHeight), 183, 21) label.backgroundColor = UIColor.whiteColor() label.textColor = UIColor(red: 90/255.0, green: 187/255.0, blue: 206/255.0, alpha: 1.0) label.textAlignment = NSTextAlignment.Left label.font = UIFont (name: "HelveticaNeue-Light", size: 14) label.text = " \(peop.getName()) - \(sex)" self.scrollView.addSubview(label) //Delete button var button = UIButton.buttonWithType(UIButtonType.System) as UIButton button.tag = playerId button.frame = CGRectMake(199, CGFloat(nameHeight), 37, 21) button.backgroundColor = colorWheel.colorsArray[7] button.setTitle("Slet", forState: UIControlState.Normal) button.addTarget(self, action: "delAction:", forControlEvents: UIControlEvents.TouchUpInside) button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) self.scrollView.addSubview(button) button.titleLabel!.font = UIFont(name: "HelveticaNeue-Light", size: 14) scrollHeight = scrollHeight + 29 nameHeight = nameHeight + 29 playerId++ } scrollView.contentSize = CGSize(width: 20.0, height: CGFloat(nameHeight)) } func delAction(sender: UIButton!){ personArray.removeAtIndex(sender.tag) updatePeople() } 
+5
ios swift uiscrollview
Nov 21 '14 at 15:29
source share
4 answers

Have you tried this?

 let subViews = self.scrollView.subviews for subview in subViews{ subview.removeFromSuperview() } 
+18
Nov 21 '14 at 15:43
source share

Single line solution, use

 scrollView.subviews.forEach({ $0.removeFromSuperview() }) 

UPDATED

To remove only a specific view, say UIButton use

 scrollView.subviews.forEach ({ ($0 as? UIButton)?.removeFromSuperview() }) 
+15
Apr 27 '15 at 7:32
source share

You can do this with a block approach,

 let views: NSArray = scroller.subviews // 3 - remove all subviews views.enumerateObjectsUsingBlock { (object: AnyObject!, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in object.removeFromSuperview() } 
+1
Feb 06 '15 at 8:51
source share

Removing a set of objects from different classes can be done using tags. Set the tag when creating the feature set.

 label.tag = 99 

Now, removing objects, use:

 func removeLabels() { let subViews = self.view.subviews for subview in subViews { if subview.tag == 99 { subview.removeFromSuperview() } } } 
+1
Nov 25 '16 at 2:36
source share



All Articles