Swift addsubview并将其删除

我想添加子视图,并删除一个水龙头。 这是我的代码:

/ *添加子视图* /

var testView: UIView = UIView(frame: CGRectMake(0, 0, 320, 568)) testView.backgroundColor = UIColor.blueColor() testView.alpha = 0.5 testView.tag = 100 super.view.userInteractionEnabled = false self.view.userInteractionEnabled = true self.view.addSubview(testView) 

/ *删除子视图* /

 override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { let touch = touches.anyObject() as UITouch let point = touch.locationInView(self.view) if(testView.tag==100){ println("Tag 100") testView.removeFromSuperview() } else{ println("tag not found") } } 

但删除它不工作有人可以帮助我吗? 谢谢!

你必须使用viewWithTag函数来查找给定tag的视图。

 override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { let touch = touches.anyObject() as UITouch let point = touch.locationInView(self.view) if let viewWithTag = self.view.viewWithTag(100) { println("Tag 100") viewWithTag.removeFromSuperview() } else { println("tag not found") } } 

感谢帮助。 这是解决scheme:我创build了子视图,我添加一个手势来删除它

 @IBAction func infoView(sender: UIButton) { var testView: UIView = UIView(frame: CGRectMake(0, 0, 320, 568)) testView.backgroundColor = UIColor.blueColor() testView.alpha = 0.5 testView.tag = 100 testView.userInteractionEnabled = true self.view.addSubview(testView) let aSelector : Selector = "removeSubview" let tapGesture = UITapGestureRecognizer(target:self, action: aSelector) testView.addGestureRecognizer(tapGesture) } func removeSubview(){ println("Start remove sibview") if let viewWithTag = self.view.viewWithTag(100) { viewWithTag.removeFromSuperview() }else{ println("No!") } } 

更新:

Swift 3+

 @IBAction func infoView(sender: UIButton) { let testView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568)) testView.backgroundColor = .blue testView.alpha = 0.5 testView.tag = 100 testView.isUserInteractionEnabled = true self.view.addSubview(testView) let aSelector : Selector = #selector(GasMapViewController.removeSubview) let tapGesture = UITapGestureRecognizer(target:self, action: aSelector) testView.addGestureRecognizer(tapGesture) } func removeSubview(){ print("Start remove sibview") if let viewWithTag = self.view.viewWithTag(100) { viewWithTag.removeFromSuperview() }else{ print("No!") } } 

使用XCode 8和Swift 3testing了这个代码

将自定义视图添加到SuperView使用:

self.view.addSubview(MyView的)

从Superview中删除自定义视图使用:

self.view.willRemoveSubview(MyView的)