[英]Can I add a new cell to a tableview, when I press a button in swift, with some text from a textfield?
所以我才剛剛開始學習敏捷,對此我有些困惑。
我有這個表視圖的例子。 從代碼中的數組中插入了3個文本...但是我想用我在文本字段中放置的一些文本來完成該數組...-> @IBOutlet weak var inputMessage: UITextField!
,並且我想在按下按鈕后添加文本: @IBAction func sendMsg(sender: AnyObject)
...我不知道如何為要插入的每個文本在表格中創建一個單元格...
可以這樣做嗎? 如果是,您能給點提示嗎?
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//table view
@IBOutlet weak var tableView: UITableView!
//input field
@IBOutlet weak var inputMessage: UITextField!
//text arrays
var textArray: NSMutableArray! = NSMutableArray()
//var input = inputMessage.text
//push the button
///when you press the button create a label and put in a cell view
@IBAction func sendMsg(sender: AnyObject) {
var input = inputMessage.text
self.textArray.addObject(input)
//make rows change their dimensions
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 44.0
self.textArray.addObject(input)
func viewDidLoad() {
super.viewDidLoad()
}
}
// the view did load function
override func viewDidLoad() {
super.viewDidLoad()
self.textArray.addObject("Before You Say I Can'T, Make Sure You'Ve Tried.")
self.textArray.addObject("-I'm a mirror. If you're cool with me, I'm cool with you, and the exchange starts. What you see is what you reflect. If you don't like what you see, then you've done something. If I'm standoffish, that's because you are.")
self.textArray.addObject("It seems like once people grow up, they have no idea what's cool.")
var input = inputMessage.text
//make rows change their dimensions
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 44.0
}
// the did received memory warning
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Table View Delegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.textArray.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
cell.textLabel?.text = self.textArray.objectAtIndex(indexPath.row) as? String
return cell
}
}
謝謝!
在向textArray
添加新元素后,只需重新加載tableView即可, textArray
所示:
self.textArray.addObject(input)
self.tableView.reloadData()
然后將對象兩次添加到textArray
。
因此刪除self.textArray.addObject(input)
您的操作方法將是:
@IBAction func sendMsg(sender: AnyObject) {
var input = inputMessage.text
//make rows change their dimensions
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 44.0
self.textArray.addObject(input)
tableView.reloadData()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.