Swift添加子视图并将其删除 [英] Swift addsubview and remove it

查看:583
本文介绍了Swift添加子视图并将其删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加子视图并点按一下即可删除。
这是我的代码:

I want to add sub view and remove with one tap. This is my code:

/ *添加子视图* /

/* To add subview */

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)

/ *删除子视图* /

/* To remove subview */

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")
    }

}

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

But the remove it isn't working Someone can help me please? Thanks!

推荐答案

感谢您的帮助。这是解决方案:
我创建了子视图,我添加了一个删除它的手势

Thanks for help. This is the solution: I created the subview and i add a gesture to remove it

@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!")
    }
}

这篇关于Swift添加子视图并将其删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆