2016-10-20 47 views
1

我使用以下代碼在用戶每次輸入消息並單擊「發送」時添加新消息。它效果很好。但問題是,新消息插入在表視圖的頂部。我希望它被插入底部。如何在tableview底部添加新行 - 聊天消息

import UIKit 

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 

    @IBOutlet var messagesTable: UITableView! 
    @IBOutlet var messageTextBox: UITextField! 

    var messageArray = [String]() 

    @IBAction func sendMessage(sender: AnyObject) { 

     messageArray.append(messageTextBox.text!) 
     messagesTable.reloadData() 
     messageTextBox.text = "" 

    } 


    override func viewDidLoad() { 
     super.viewDidLoad() 
    } 


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return messageArray.count 
    } 

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
     return 80 
    } 

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


     //self.messagesTable.contentInset = UIEdgeInsetsMake(messagesTable.frame.height,0,0,0) 

     let cell = NSBundle.mainBundle().loadNibNamed("AgentMessageText", owner: self, options: nil)?.first as! AgentMessageText 
     cell.messageText.text = messageArray[indexPath.row] 
     return cell 
    } 

} 

下面的代碼將行插入底部。但新插入的行在視點之下。這是我們必須滾動才能看到它每一次

self.messagesTable.contentInset = UIEdgeInsetsMake(messagesTable.frame.height,0,0,0) 
+0

爲y見此我們的代碼將您的消息插入底部而不是頂部。你面臨的問題是你必須滾動才能看到它們,對吧? –

+0

將消息添加到您的messageArray並使用'insertRowsAtIndexPaths'插入您的行,然後使用'scrollToRowAtIndexPath'滾動到新添加的消息 – NSNoob

+0

此外,爲了將消息添加到頂部,您必須告訴我們如何更新您的數據源數組用於新消息。正如Inder Kumar Rathore所說,你的單元格不應該在底部添加你的'cellForRowAtIndexPath'。沒有必要重新加載整個TableView,你可以使用scrollToRowAtIndexPath並滾動到最後一個元素 – NSNoob

回答

2

這一問題的常見方法是翻轉的tableview(使細胞粘在底部),然後翻轉細胞,使內容的方向正確。

例子:

override func viewDidLoad() { 
    super.viewDidLoad() 

    //flips the tableview (and all cells) upside down 
    messagesTableView.transform = CGAffineTransformMakeScale(1, -1) 
} 

...

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

    ... 

    //flips the cell to appear oriented correctly 
    cell.transform = CGAffineTransformMakeScale(1, -1) 
+0

是的。如果你能告訴我代碼 –

+0

好,這將是一個很大的幫助。看起來很棒!! –

0

您對使用scrollToRow滾動到你的信息(。使用.bottom/.TOP/ACC等你的需要) 此外,而不是重裝整個表視圖,您可以添加只有一個(新的)消息(小區),以表視圖

@IBAction func sendMessage(sender: AnyObject) { 
    messageArray.append(messageTextBox.text!) 
    messagesTable.reloadData() 
    let indexPath = IndexPath(item: messageArray.count, section: 0) 
    messagesTable.scrollToRow(at: indexPath, at: .bottom, animated: true) 
    messageTextBox.text = "" 
} 
+0

我得到一個錯誤:「使用未解析的標識符'indexPath' –

+0

您使用的是swift 3嗎? –

+0

no swift 2,xcode 7.3 –