我有一个 uiscrollview,它的高度与主视图不同。我在这个 ScrollView 之外有一个 uitextfield 和一个按钮。我在其中输入一个值,然后单击按钮,它会在 ScrollView 内创建另一个文本字段,然后如果我再次按下,它将在先前创建的文本字段下方创建另一个文本字段。现在,我尝试将 View 滚动到新创建的文本字段,该文本字段应该在键盘 View 上方可见。我已经尝试过以下方法。它不起作用:
func keyboardWillShow() {
var userInfo = notification.userInfo!
var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
let textField: UITextField = self.scrollView!.viewWithTag(rowsCount) as! UITextField
let newRect: CGRect = CGRectMake(textField.frame.origin.x, textField.frame.origin.y, textField.frame.width, textField.frame.height)
let newFrame = self.view.convertRect(newRect, fromView: nil)
keyboardFrame = self.view.convertRect(keyboardFrame, fromView: nil)
// contentInset.bottom = newRect.origin.y + newRect.height
var viewRect: CGRect = self.view.frame
viewRect.size.height = viewRect.height - keyboardFrame.height - 40.0
if (!CGRectContainsPoint(viewRect, (newFrame.origin))) {
self.scrollView.scrollRectToVisible((newFrame), animated: true)
}
}
P.S.:每次创建新文本字段时,rowsCount 都会增加。
最佳答案
你可以这样做,
scrollView.scrollRectToVisible(CGRect(x: x, y: y, width: 1, height: 1), animated: true)
// or
scrollView.setContentOffset(CGPoint(x: x, y: y), animated: true)
点击按钮时将你的 x 和 y 传递给它。
关于ios - Swift:滚动不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39117193/