我写了一个在触摸外部子视图时解除子视图的方法。这是我的示例代码演示:
import UIKit
class ViewController: UIViewController {
var testView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
let frame = CGRect(x: 10.0, y: 10.0, width: 100.0, height: 100.0)
print("origin frame is \(frame)")
testView = UIView(frame: frame)
testView.center = self.view.center
testView.backgroundColor = UIColor.greenColor()
testView.userInteractionEnabled = true
print("frame of test View is \(testView.frame)")
self.view.addSubview(testView)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
//got point of touch
if let touchPlace = touches.first?.locationInView(view) {
print("Your touch was at \(touchPlace)")
let isInside = testView.pointInside(touchPlace, withEvent: nil)
print("Will touch be inside subview? Answer: \(isInside)")
if !isInside {
testView.removeFromSuperview()
}
}
}
}
然而,isInside
总是假的,尽管有触摸的位置。这是控制台文本:
origin frame is (10.0, 10.0, 100.0, 100.0)
frame of test View is (157.0, 318.0, 100.0, 100.0)
Your touch was at (168.33332824707, 330.666656494141)
Will touch be inside subview? Answer: false
显然,触摸点在testView
内部,并且我不知道如何使其工作。
提前致谢!
答案 0 :(得分:1)
point
方法的pointInside
参数定义为:
接收者本地坐标系中的一个点(界限)。
相反,您希望针对textView
的框架测试触摸点,该坐标系与触摸点(超视图坐标系)位于同一坐标系中:
let isInside = CGRectContainsPoint(testView.frame, touchPlace)