2015-12-16 2 views
0

Как добавить текст в tableViewCell? Я перетащил один textfield и button, и добавьте под ними, установите tableView и tableviewCell. Идентификатором ячейки является «Ячейка». И вот код, который я сделал до сих пор. В идеале я хочу добавить в ячейку тексты, напечатанные внутри textfield, так что, например, если я добавлю свое имя, оно будет добавлено, и если следующий человек добавит ее имя, ее имя также появится в ячейке.Как добавить тексты в каждую ячейку, используя текстовое поле и кнопку?

@IBOutlet weak var myTableView: UITableView! 
@IBOutlet weak var textField: UITextField! 

var stringArray = [String]() 
@IBOutlet weak var AddBUtton: UIButton! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    textField.delegate = self 
} 

func textFieldDidBeginEditing(textField: UITextField) { 
} 
func textFieldDidEndEditing(textField: UITextField) { 
} 
func textFieldShouldBeginEditing(textField: UITextField) -> Bool { 
    return true 
} 
func textFieldShouldClear(textField: UITextField) -> Bool { 
    return true 
} 
func textFieldShouldEndEditing(textField: UITextField) -> Bool { 
    return true 
} 
func textFieldShouldReturn(textField: UITextField) -> Bool { 
    textField.resignFirstResponder() 
    return true 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cellIdentifier = "Cell" 
    let cell = self.myTableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! UITableViewCell 
    return cell 
} 

ответ

1

Просто попробуйте установить TextLabel из UITableViewCell

func textFieldShouldReturn(textField: UITextField) -> Bool { 
    stringArray.append(textField.text) 
    textField.text = nil 
    textField.resignFirstResponder() 
    table.reloadData() // if possible just reload or insert only the cell 
    return true 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cellIdentifier = "Cell" 
    let cell = self.myTableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! UITableViewCell 
    cell.textLabel.text = stringArray[indexPath.row] 
    return cell 
} 
+0

Спасибо! Это сработало!! Теперь я подумал, что было бы очень здорово, если бы я мог добавить больше функций в этот проект, например, когда я вводил слова в своем текстовом поле, он упорядочивался по алфавиту. Вы знаете, как это сделать? –

+0

каждый раз, когда вы добавляете строку в массив, вы просто сортируете ее перед перезагрузкой, например. 1) stringArray.append (textField.text) 2) stringArray.sort // как сортировать, mm выяснить себя – RJE

0

Вы можете создать собственный UITableViewCell класс, который наследуется от UITableViewCell. Оттуда вы можете добавить переменную для хранения любого текста, который вы получаете от textfield.

После этого вы можете использовать эту ячейку в качестве новой ячейки внутри вашего метода cellForRowAtIndexPath.

+0

Спасибо за ваше участие! Эта проблема решена! –

0

Попробуйте this control внутри пользовательского UITableViewCell. Каждый раз, когда имя вводится в текстовое поле, добавьте это имя в источник данных этого элемента управления, чтобы он появился в следующий раз в списке предложений. У вас есть возможность фильтровать текст по типу пользователя (при необходимости).

+0

Спасибо! Эта проблема решена :) –

0

Попробуйте сделать что-то вроде этого:

@IBOutlet weak var text: UITextField! 

@IBOutlet weak var button: UIButton! 
@IBOutlet weak var tableView: UITableView! 

var name:NSMutableArray = NSMutableArray(); 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    self.tableview.delegate = self;   
    self.tableView.dataSource = self; 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

@IBAction func buttonClicked(sender: AnyObject) { 
    if(self.text.text == ""){ 
     let alert = UIAlertController(title: "Alert", message: "Enter a name", preferredStyle: UIAlertControllerStyle.Alert) 
     alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) 
     self.presentViewController(alert, animated: true, completion: nil); 
    } 
    self.name.addObject(self.text.text!) 
    self.text.text = ""; 
    self.tableView.reloadData(); 
} 

func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return 1; 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cellIdentifier = "Cell"; 
    var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier); 
    if(cell == nil){ 
     cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: cellIdentifier); 
    } 

    cell?.textLabel?.text = self.name[indexPath.row] as? String 

    return cell!; 
} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return self.name.count; 
} 
+0

Спасибо за ваше время и помощь! Эта демонстрация была немного сложной для меня, новичка, но стоило узнать, какая интересная функция я попытаюсь научиться использовать;) –

Смежные вопросы