現在Viewの中にtextFieldとtextViewがあります
textViewがタップされたらViewをスクロールさせたいのですが
今のコードでは1度textViewがタッチされると以降textFieldでもviewがスクロールしてしまします。
原因は
swift
1 func isTouch(touches: Set<UITouch>, view:UIView) -> Bool{ 2 for touch: AnyObject in touches { 3 let t: UITouch = touch as! UITouch 4 if t.view?.tag == view.tag { 5 return true 6 } else { 7 return false 8 } 9 } 10 return false 11 }
ここででviewがスクロールする処理が1度解除されると以降textFieldにも適用されてしまうと考えていますが対処の仕方が分からない状態です
swift
1import UIKit 2 3class testViewController: UIViewController, UITextViewDelegate, UIScrollViewDelegate, UITextFieldDelegate { 4 5 6 @IBOutlet weak var textView: UITextView! 7 @IBOutlet weak var textField: UITextField! 8 9 override func viewDidLoad() { 10 super.viewDidLoad() 11 textView.delegate = self 12 textField.delegate = self 13 textView.tag = 123 14 15 } 16 17 18 19 func configureObserver() { 20 21 let notification = NotificationCenter.default 22 23 notification.addObserver( 24 self, 25 selector: #selector(self.keyboardWillShow(notification:)), 26 name: UIResponder.keyboardWillShowNotification, 27 object: nil 28 ) 29 30 notification.addObserver( 31 self, 32 selector: #selector(self.keyboardWillHide(notification:)), 33 name: UIResponder.keyboardWillHideNotification, 34 object: nil 35 ) 36 } 37 38 // Notificationを削除 39 func removeObserver() { 40 NotificationCenter.default.removeObserver(self) 41 } 42 43 44 // キーボードが現れたときにviewをずらす 45 @objc func keyboardWillShow(notification: Notification?) { 46 let rect = (notification?.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue 47 let duration: TimeInterval? = notification?.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double 48 UIView.animate(withDuration: duration!) { 49 self.view.transform = CGAffineTransform(translationX: 0, y: -(rect?.size.height)!) 50 51 } 52 } 53 54 // キーボードが消えたときにviewを戻す 55 @objc func keyboardWillHide(notification: Notification?) { 56 let duration: TimeInterval? = notification?.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? Double 57 UIView.animate(withDuration: duration!) { 58 self.view.transform = CGAffineTransform.identity 59 } 60 } 61 62 63 64 65 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 66 if isTouch(touches: touches, view: textView) { 67 self.configureObserver() 68 69 70 } 71 } 72 73 func isTouch(touches: Set<UITouch>, view:UIView) -> Bool{ 74 for touch: AnyObject in touches { 75 let t: UITouch = touch as! UITouch 76 if t.view?.tag == view.tag { 77 return true 78 } else { 79 return false 80 } 81 } 82 return false 83 } 84 85 86
回答2件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
2019/06/13 13:40 編集