每次用户键入消息并单击“发送”时,我都会使用以下代码添加新消息。效果很好。但问题是,新消息被插入到表视图的顶部。我希望将其插入底部。
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)
此问题的常见解决方案是翻转表格视图(使单元格粘在底部),然后翻转单元格以使内容正确定向。
Example:
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)
对于斯威夫特 4
需要明确的是,对于 Swift 4.0,上述转换函数如下所示
CGAffineTransform(scaleX: 1, y: -1)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)