user4591756
user4591756

Reputation:

Swift: TableView scroll to position

Maybe this is the wrong way of doing this so please show me the correct way if its wrong. I have a tableview on a scrollview. Most cells have a TextField which onclick it shows the keyboard. The problem I am having is that cells at the bottom of the scroll view end up getting stuck behind the keyboard.

// I build the tableView
self.shippingTableView = UITableView(frame: CGRectMake(0, 5, self.view.frame.width, CGFloat(tableViewHeight)))
self.shippingTableView.delegate = self
self.shippingTableView.dataSource = self
self.shippingTableView.scrollEnabled = true
self.scrollView.addSubview(self.shippingTableView)

// Create some delegate methods
// I know i'm not reusing cells yet but will update later.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.accessoryType = UITableViewCellAccessoryType.None

    let textField = UITextField(frame: CGRectMake(10, 0, cell.frame.width, cell.frame.height))
    textField.delegate = self
    cell.contentView.addSubview(textField)
    return cell
}

Now from the above code I have the view on the page and if i select a item, the keyboard shows but with the cell behind. I created my delegate method and tried the following. I added a print line to this method so I know its getting called.

func textFieldDidBeginEditing(textField: UITextField) {
    let indexPath = NSIndexPath(forItem: textField.tag, inSection: 0)

    // I tried each of the following separatly, but nothing moves.
    self.shippingTableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: true)
    self.shippingTableView.scrollToNearestSelectedRowAtScrollPosition(UITableViewScrollPosition.Middle, animated: true)
}

I guessed the problem was because I had a tableView within a scrollView but I tried changing this to just a standard view and had the same problem.

Surely the correct answer is not to scroll manually?

Upvotes: 1

Views: 1327

Answers (1)

Tejas Ardeshna
Tejas Ardeshna

Reputation: 4373

First don't add UITableView in UIScrollView. Download TPKeyboardAvoiding make TPKeyboardAvoidingTableView as super class of tableview. And you don't have to worry about scroll tableview manually, TPKeyboard will handle automatically.

Upvotes: 3

Related Questions