0

I found this solution for objective-c: Scroll UITextField above Keyboard in a UITableViewCell on a regular UIViewController but I can't adapt it for 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
}

I get error :

Value of optional type 'CGFloat?' not unwrapped; did you mean to use '!' or '?'?  

When I use ! or ? I get error: Operand of postfix '?' should have optional type; type is 'CGFloat'

Community
  • 1
  • 1
Walter West
  • 829
  • 3
  • 12
  • 31

1 Answers1

9

This is one way to avoid the error in your code:

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
}

First of all, we can assume textView has a superview, so we can unwrap it with !.
As a result, pointInTable is not optional anymore.
If we assume textView might not have an inputAccessoryView, we can use the typical if let syntax to check if inputAccessoryView exists and, if so, subtract its height from contentOffset.y.
Don't forget to assign contentOffset to your tableView and return a Bool.

Para
  • 3,681
  • 4
  • 23
  • 34
  • its moving too much.. can i make the distance of movement lesser?? – SaiPavanParanam Dec 05 '16 at 09:20
  • @SaiPavanParanam absolutely! Please try different values of `contentOffset` until you find the one that suits you best. – Para Dec 05 '16 at 09:46
  • @Para Great answer – huddie96 Aug 29 '17 at 00:45
  • @Para this code scrolls my textview to the very top of the screen rather than just above the keyboard. Can you advise on how this might be fixed? I know I can add static numbers to the contentOffset but I'm more interested in finding out why your code doesn't put it exactly above the keyboard? – user2363025 Nov 20 '18 at 09:19
  • @SaiPavanParanam did you figure this out? – user2363025 Nov 20 '18 at 09:21