错误描述:
如下图所示,我需要仿照微信,做一个录制、发送、取消录制语音的功能,但当手指移出“长按 开始”区域后,touchesEnd方法监听不到手指离开屏幕的事件。。。
在我的实现中,下方输入栏输入栏(红色矩形框起来的区域)是一个单独的view,用一个单独的类进行管理,其touch方法实现如下:
//触摸开始
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//开始录音
self.beginRecord()
let touch = touches.first
if let _ = touch?.location(in: self.voicePressView) {
print("按到录音按钮,开始讲话。。")
self.voicePressView.text = "长按 结束"
self.voicePressView.backgroundColor = UIColor.colorWithRGB(198, green: 199, blue: 202, alpha: 1)
}
}
//手指移动(输入栏)
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if let y = touch?.location(in: self.voicePressView).y{
if y < 0 {
if self.isRecordCancel == false {
self.isRecordCancel = true
}
}else {
if self.isRecordCancel {
self.isRecordCancel = false
}
}
}
}
//手指从屏幕拿起(输入栏)
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if self.voicePressView.text == "长按 结束"{
self.endRecord()
}
self.voicePressView.text = "长按 开始"
self.voicePressView.backgroundColor = UIColor.colorWithRGB(235, green: 240, blue: 243, alpha: 1)
}
如开篇所说,当手指移出输入栏区域,touchesend方法监听不到手指离开屏幕事件了!如图,此时就没办法将录音状态提示框(屏幕中间的灰色方框)移出了

[图片上传中...(截图.png-4a22b9-1538033146585-0)]
问题的分析:
因为手指不是在监听的视图离开的,自然监听不到touchesEnd方法。
改进
在聊天界面写上touchesEnd监听。。。
结果
失败
改进
查阅得知,需要在子视图上添加
superview?.touchesBegan(touches, with: event)
super.touchesMoved(touches, with: event)
super.touchesEnded(touches, with: event)
成功
聊天界面重要监听到了touchesEnd方法。。
值得注意的是:如果只写
super.touchesEnded(touches, with: event)
不写
superview?.touchesBegan(touches, with: event)
super.touchesMoved(touches, with: event)
同样也是监听不到的。
修改后
输入栏的touch方法
//触摸开始
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//开始录音
self.beginRecord()
let touch = touches.first
if let _ = touch?.location(in: self.voicePressView) {
print("按到录音按钮,开始讲话。。")
self.voicePressView.text = "长按 结束"
self.voicePressView.backgroundColor = UIColor.colorWithRGB(198, green: 199, blue: 202, alpha: 1)
}
super.touchesBegan(touches, with: event)
}
//手指移动(输入栏)
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
//
let touch = touches.first
if let y = touch?.location(in: self.voicePressView).y{
if y < 0 {
if self.isRecordCancel == false {
self.isRecordCancel = true
}
}else {
if self.isRecordCancel {
self.isRecordCancel = false
}
}
}
super.touchesMoved(touches, with: event)
}
//手指从屏幕拿起(输入栏)
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if self.voicePressView.text == "长按 结束"{
self.endRecord()
}
self.voicePressView.text = "长按 开始"
self.voicePressView.backgroundColor = UIColor.colorWithRGB(235, green: 240, blue: 243, alpha: 1)
super.touchesEnded(touches, with: event)
}
聊天界面touch方法
//触摸结束,移除录音状态视图
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.tableView.isUserInteractionEnabled = true
self.recordV.removeFromSuperview()
super.touchesEnded(touches, with: event)
}
网友评论