【问题标题】:Managing keyboard with scroll view使用滚动视图管理键盘
【发布时间】:2017-04-18 02:00:07
【问题描述】:

我目前正在学习来自 raywenderlich 的关于滚动视图的课程。有一个课程是关于如何将观察者添加到通知中心以跟踪键盘何时显示。这是代码的外观。

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)


func keyboardWillHide(notification: Notification) {
    adjustKeyboardInset(false, notification: notification)
}

func keyboardWillShow(notification: Notification) {
    adjustKeyboardInset(true, notification: notification)
}

func adjustKeyboard(isShown: Bool, notification: Notification) {
    let userInfo = notification.userInfo ?? [:]
    let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue

    let adjustedHeight = keyboardFrame.height * (isShown ? 1 : -1) + 20

    mySV.contentInset.bottom += adjustedHeight
    mySV.scrollIndicatorInsets.bottom += adjustedHeight
}

这在第一次单击文本字段时可以正常工作。但是,当您继续单击 textField 时,它会不断为其添加空间。

不胜感激。 :)

【问题讨论】:

    标签: ios swift3 uiscrollview


    【解决方案1】:

    最好不要使用“+=”操作。替代解决方案可能是:

    var originalBottom:CGFloat = 0.0
    var originalIndicatorBottom:CGFloat = 0.0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        originalBottom = mySV.contentInset.bottom.constant
        originalIndicatorBottom:CGFloat = mySV.scrollIndicatorInsets.bottom.constant
    }
    
    //......    
    
    func adjustKeyboard(isShown: Bool, notification: Notification) {
        let userInfo = notification.userInfo ?? [:]
        let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
    
        let adjustedHeight = keyboardFrame.height + 20
    
        if isShown {
            mySV.contentInset.bottom = originalBottom + adjustedHeight
            mySV.scrollIndicatorInsets.bottom = originalIndicatorBottom + adjustedHeight
        }
        else
        {
           mySV.contentInset.bottom = originalBottom 
           mySV.scrollIndicatorInsets.bottom = originalIndicatorBottom 
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-02
      • 2017-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-09
      相关资源
      最近更新 更多