ios - Swift:滚动不起作用

标签 ios swift uiscrollview uitextfield cgrect

我有一个 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/

相关文章:

arrays - fatal error : Index out of Range Swift 3. 1

swift - Swift 中字符串插值和字符串初始值设定项之间的区别

ios - 为什么我不能在 Swift 中使用 let in 协议(protocol)?

ios - 防止 UIDatePicker 变得太宽

ios - 在 iPad 10.5 英寸模拟器中运行应用程序?

ios - 我可以使用 AVAudioPlayer 播放带有振动的声音吗?

ios - 将焦点添加到 Popover 中的 TextView

ios - AirPlay 没有出现在 iOS 10 中

ios - ScrollView 在编译时不滚动

iOS : ScrollView delegate method inside of CollectionView not call