サブビューを追加して、ワンタップで削除したいです。これは私のコードです:
/ *サブビューを追加するには* /
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!")
}
}
更新:
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!")
}
}
指定された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) {
print("Tag 100")
viewWithTag.removeFromSuperview()
} else {
print("tag not found")
}
}