現在Viewの中にtextFieldとtextViewがあります
textViewがタップされたらViewをスクロールさせたいのですが
今のコードでは1度textViewがタッチされると以降textFieldでもviewがスクロールしてしまします。
原因は
swift
func isTouch(touches: Set<UITouch>, view:UIView) -> Bool{ for touch: AnyObject in touches { let t: UITouch = touch as! UITouch if t.view?.tag == view.tag { return true } else { return false } } return false }
ここででviewがスクロールする処理が1度解除されると以降textFieldにも適用されてしまうと考えていますが対処の仕方が分からない状態です
swift
import UIKit class testViewController: UIViewController, UITextViewDelegate, UIScrollViewDelegate, UITextFieldDelegate { @IBOutlet weak var textView: UITextView! @IBOutlet weak var textField: UITextField! override func viewDidLoad() { super.viewDidLoad() textView.delegate = self textField.delegate = self textView.tag = 123 } func configureObserver() { let notification = NotificationCenter.default notification.addObserver( self, selector: #selector(self.keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil ) notification.addObserver( self, selector: #selector(self.keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil ) } // Notificationを削除 func removeObserver() { NotificationCenter.default.removeObserver(self) } // キーボードが現れたときにviewをずらす @objc func keyboardWillShow(notification: Notification?) { let rect = (notification?.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue let duration: TimeInterval? = notification?.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double UIView.animate(withDuration: duration!) { self.view.transform = CGAffineTransform(translationX: 0, y: -(rect?.size.height)!) } } // キーボードが消えたときにviewを戻す @objc func keyboardWillHide(notification: Notification?) { let duration: TimeInterval? = notification?.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? Double UIView.animate(withDuration: duration!) { self.view.transform = CGAffineTransform.identity } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if isTouch(touches: touches, view: textView) { self.configureObserver() } } func isTouch(touches: Set<UITouch>, view:UIView) -> Bool{ for touch: AnyObject in touches { let t: UITouch = touch as! UITouch if t.view?.tag == view.tag { return true } else { return false } } return false }
まだ回答がついていません
会員登録して回答してみよう