我找到了针对objective-c的解决方案:在常规UIViewController上的UITableViewCell中将键盘上方的UITextField滚动,但我无法将其改编为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
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
Value of optional type 'CGFloat?' not unwrapped; did you mean to use '!' or '?'?
Run Code Online (Sandbox Code Playgroud)
我用的时候!要么 ?我收到错误:postfix的操作数'?' 应该有可选的类型; 类型是'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
}
Run Code Online (Sandbox Code Playgroud)
首先,我们可以假设textView有一个superview,所以我们可以打开它!.
结果,pointInTable不再是可选的.
如果我们假设textView可能没有inputAccessoryView,我们可以使用典型的if let语法来检查是否inputAccessoryView存在,如果是,则从中减去它的高度contentOffset.y.
不要忘记分配contentOffset给你tableView并返回一个Bool.