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

}

}

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

回答:

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

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

}

}

更新:

@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 addsubview并将其删除 的全部内容, 来源链接: utcz.com/qa/421411.html

回到顶部