我有一个UIScrollView,我在其上放置了一些文本字段和一个tableView。
这不是表委托问题。如果我点击并拖动一行,我可以获得didSelectRowAt。只是简单的行点击无法通过。
我没有在下面显示表格实现,因为它通常有效,我认为这是造成问题的手势位。
我在UIScrollView中添加了一个手势识别器,这样如果点击视图背景,您将结束当前字段的编辑。这可以解除编辑和键盘,但对于 UITableView ,当我点击一行时,我没有得到didSelectRowAt。我必须按行并水平拖动才能获得didSelectRowAt方法调用。
有没有办法将点击手势转发到UITableView?或者,如果我在该视图上有一个表格,那么在UIScrollView上使用手势识别器是一个坏主意吗?同一视图上的按钮将获取点击并处理按钮事件。不知道为什么表不会获得点击。该表格也会正确滚动,但看不到行敲击。
主要的UIView类方法
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 1, alpha: 1.0) // was .97
// Container
setupScrollView()
registerKeyboardNotifications()
addGestureRecognizer()
}
func setupScrollView() {
view.addSubview(scrollView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.contentSize = CGSize(width: view.frame.width, height: 1000)
scrollView.autoresizingMask = UIViewAutoresizing.flexibleBottomMargin
scrollView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
scrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
scrollView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: 0).isActive = true
scrollView.heightAnchor.constraint(equalTo: view.heightAnchor, constant: 0).isActive = true
}
func addGestureRecognizer() {
// When tap on the container -- end editing on current field
let tapRecognizer = UITapGestureRecognizer(target: self,action: #selector(tapDidTouch(sender: )))
self.scrollView.addGestureRecognizer(tapRecognizer)
}
@objc func tapDidTouch(sender: Any) { // this method eats UITableView clicks
self.view.endEditing(true)
}
处理键盘的扩展程序
extension TestView {
func registerKeyboardNotifications() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self,selector: #selector(keyboardWillShow(notif:)),name: .UIKeyboardWillShow,object: nil)
notificationCenter.addObserver( self, selector: #selector(keyboardWillHide(notif:)),name: .UIKeyboardWillHide,object: nil)
notificationCenter.addObserver(self, selector: #selector(keyboardWillShow(notif:)), name: .UIKeyboardWillChangeFrame, object: nil)
}
@objc func keyboardWillShow(notif: Notification) {
guard let frame = notif.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect else { return}
scrollView.contentInset = UIEdgeInsets(top: 0.0,
left: 0.0,
bottom: frame.height,
right: 0.0)
}
@objc func keyboardWillHide(notif: Notification) {
scrollView.contentInset = UIEdgeInsets()
}
}