XcodeでScroll View自身とScrollVIew内の部品にAuto Layoutを適用させたいです。
いつも通り、Scroll View内の部品に制約をつけるとビルドした時に真っ白になってしまします。何か方法はありますか?
具体的にしたいこととしては、text Fieldを編集するときにtext FIeldが隠れないようにしたいです。
コードは参考サイトと全く同じように書きました。
Swift
1import UIKit 2 3class ViewController: UIViewController { 4 @IBOutlet weak var scrollview: UIScrollView! 5 @IBOutlet weak var textView: UITextField! 6 @IBOutlet weak var label: UILabel! 7 @IBOutlet weak var orange: UIView! 8 9 var screenHeight:CGFloat! 10 // Screenの幅 11 var screenWidth:CGFloat! 12 13 override func viewDidLoad() { 14 super.viewDidLoad() 15 16 scrollview.delegate = (self as? UIScrollViewDelegate) 17 textView.delegate = self as? UITextFieldDelegate 18 // Do any additional setup after loading the view, typically from a nib. 19 20 let screenSize: CGRect = UIScreen.main.bounds 21 screenWidth = screenSize.width 22 screenHeight = screenSize.height 23 scrollview.frame.size = 24 CGSize(width: screenWidth, height: screenHeight) 25 scrollview.addSubview(orange) 26 scrollview.addSubview(label) 27 scrollview.addSubview(textView) 28 scrollview.contentSize = CGSize(width: screenWidth, height: screenHeight*2) 29 scrollview.bounces = false 30 print("screenWidth:(screenWidth)") 31 print("screenHeight:(screenHeight)") 32 33 } 34 func textFieldShouldReturn(_ textField: UITextField) -> Bool { 35 self.view.endEditing(true) 36 return true 37 } 38 39 override func viewWillAppear(_ animated: Bool) { 40 super.viewWillAppear(animated) 41 42 NotificationCenter.default.addObserver(self, 43 selector: #selector(ViewController.keyboardWillShow(_:)), 44 name: NSNotification.Name.UIKeyboardWillShow, 45 object: nil) 46 NotificationCenter.default.addObserver(self, 47 selector: #selector(ViewController.keyboardWillHide(_:)) , 48 name: NSNotification.Name.UIKeyboardWillHide, 49 object: nil) 50 } 51 52 override func viewWillDisappear(_ animated: Bool) { 53 super.viewWillDisappear(animated) 54 55 NotificationCenter.default.removeObserver(self, 56 name: .UIKeyboardWillShow, 57 object: self.view.window) 58 NotificationCenter.default.removeObserver(self, 59 name: .UIKeyboardDidHide, 60 object: self.view.window) 61 } 62 63 @objc func keyboardWillShow(_ notification: Notification) { 64 65 let info = notification.userInfo! 66 67 let keyboardFrame = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue 68 69 // bottom of textField 70 let bottomTextField = textView.frame.origin.y + textView.frame.height 71 // top of keyboard 72 let topKeyboard = screenHeight - keyboardFrame.size.height 73 // 重なり 74 let distance = bottomTextField - topKeyboard 75 76 if distance >= 0 { 77 // scrollViewのコンテツを上へオフセット + 20.0(追加のオフセット) 78 scrollview.contentOffset.y = distance + 20.0 79 } 80 } 81 82 @objc func keyboardWillHide(_ notification: Notification) { 83 scrollview.contentOffset.y = 0 84 } 85 86 override func didReceiveMemoryWarning() { 87 super.didReceiveMemoryWarning() 88 // Dispose of any resources that can be recreated. 89 } 90 91 92} 93 94
回答1件
あなたの回答
tips
プレビュー