2017-07-28 113 views
1

我找到了這個答案,但沒有任何我可以爲我的具體情況工作。Swift:當出現鍵盤時滾動UITableView

我有一個動態的原型細胞UITableView。其中一個單元格只包含UITextView,並且總是隻有其中一個,它總是在最下面。這是唯一的文本視圖。

我不能本文觀點在我的控制器,因爲它拋出一個錯誤(我假設,因爲可以有文本視圖的多個實例,他們不可能全部被映射到一個插座連接到插座)。那麼我不能讓我的控制器符合UITextView協議。

有沒有一個簡單而優雅的解決方案呢?

回答

0

嘗試觀察VC中鍵盤出現的事件。像這樣:

NotificationCenter.default.addObserver(self, selector: #selector(scrollToTop(notification:)), name: .UIKeyboardWillShow, object: nil) 
NotificationCenter.default.addObserver(self, selector: #selector(scrollToBottom(notification:)), name: .UIKeyboardWillHide, object: nil) 

func scrollToTop(notification: NSNotification) { 
     //change tableView insets 
} 


func scrollToBottom(notification: NSNotification) { 
      //change tableView insets 
} 
0

只需將您的控制器TextView的的代表在的cellForRowAtIndexPath這樣

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    ... 
    cell.textView.delegate = self 
    ... 
    return cell 
} 
0

其實你的假設,你不能讓你的視圖控制器符合UITextView的協議是錯誤的。您可以使用自定義單元格並添加將您的插座連接到此自定義單元格中的屬性。 然後,您可以將標籤分配給文本視圖,並根據標籤區分各種textView。

0

要在ViewController中設置textview的代理,您需要將其設置在cellForRowAtIndexPath中,並且您可以在viewController中訪問textview的委託方法。

片段與SWIFT 3是這裏

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    cell.yourTextView.delegate = self //Assign your textView delegate here 

} 

對於滾動tableview而鍵盤出現/消失是由NotificationCenter實現增加觀察員鍵盤出現/消失viewDidLoad如下

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil) 
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil) 

您可以檢測鍵盤顯示/使用以下方法消失

func keyboardWillShow(notification: NSNotification) { 
    print((notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size.height) 
} 


func keyboardWillHide(notification: NSNotification) { 

} 

不要忘記刪除Observer是viewLifeCycle的消失方法。

也有一些第三方的庫來實現這一這裏是其中的一些

TPKeyboardAvoiding IQKeyboardManager [建議] - 當你要滾動的tableview向上側讓你確信任何插入進入表格後將顯示在表格視圖中。以這種方式保持你的tableview,以便每當你在tableview單元格中輸入任何單個內容時,它必須被用戶看到。