我为 objective-c 找到了这个解决方案:Scroll UITextField above Keyboard in a UITableViewCell on a regular UIViewController但我不能 swift 适应它。
func textViewShouldBeginEditing(textView: UITextView) -> Bool {
var pointInTable:CGPoint? = textView.superview?.convertPoint(textView.frame.origin, toView: tableView)
var contentOffset:CGPoint = tableView.contentOffset
contentOffset.y = pointInTable?.y - textView.inputAccessoryView?.frame.size.height
}
我得到错误:
Value of optional type 'CGFloat?' not unwrapped; did you mean to use '!' or '?'?
当我使用 !或者 ?我收到错误: 后缀 '?' 的操作数应该有可选类型;类型是“CGFloat”
最佳答案
这是避免代码中错误的一种方法:
func textViewShouldBeginEditing(textView: UITextView) -> Bool {
var pointInTable:CGPoint = textView.superview!.convertPoint(textView.frame.origin, toView: tableView)
var contentOffset:CGPoint = tableView.contentOffset
contentOffset.y = pointInTable.y
if let accessoryView = textView.inputAccessoryView {
contentOffset.y -= accessoryView.frame.size.height
}
tableView.contentOffset = contentOffset
return true
}
首先,我们可以假设 textView
有一个 superview
,所以我们可以用 !
展开它。
因此,pointInTable
不再是可选的。
如果我们假设 textView
可能没有 inputAccessoryView
,我们可以使用典型的 if let
语法来检查 inputAccessoryView
存在,如果存在,则从 contentOffset.y
中减去它的高度。
不要忘记将 contentOffset
分配给您的 tableView
并返回一个 Bool
。
关于ios - 如何快速在 UITableView 中的键盘上方滚动 UITextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28297048/