2015-08-26 3 views
-2

Я делаю проект с UITableView, но я не знаю, как добавить к нему данные.Swift Xcode6 UITableView Prototype Cell

Теперь я строю свой первый взгляд, но что-то идет не так. Может кто-нибудь мне помочь?

Вот код:

import UIKit 

class WorkersListTableViewController: UITableViewController { 

    var numOfWorkersNames = [] 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Uncomment the following line to preserve selection between presentations 
     // self.clearsSelectionOnViewWillAppear = false 

     // Uncomment the following line to display an Edit button in the navigation bar for this view controller. 
     // self.navigationItem.rightBarButtonItem = self.editButtonItem() 
    } 

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

    // MARK: - Table view data source 

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     // #warning Potentially incomplete method implementation. 
     // Return the number of sections. 
     return 1 
    } 

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     // #warning Incomplete method implementation. 
     // Return the number of rows in the section. 
     return numOfWorkersNames.count 
    } 

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("WorkersCell", forIndexPath: indexPath) as! UITableViewCell 
     // Configure the cell... 
     cell. NameOfTheWorkerLabel.text = numOfWorkersNames[indexPath.row] as String 
     return cell 
    } 


    /* 
    // Override to support conditional editing of the table view. 
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { 
     // Return NO if you do not want the specified item to be editable. 
     return true 
    } 
    */ 

    /* 
    // Override to support editing the table view. 
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 
     if editingStyle == .Delete { 
      // Delete the row from the data source 
      tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) 
     } else if editingStyle == .Insert { 
      // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view 
     }  
    } 
    */ 

    /* 
    // Override to support rearranging the table view. 
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { 

    } 
    */ 

    /* 
    // Override to support conditional rearranging of the table view. 
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { 
     // Return NO if you do not want the item to be re-orderable. 
     return true 
    } 
    */ 

    /* 
    // MARK: - Navigation 

    // In a storyboard-based application, you will often want to do a little preparation before navigation 
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
     // Get the new view controller using [segue destinationViewController]. 
     // Pass the selected object to the new view controller. 
    } 
    */ 

} 

Теперь работники Cell:

class WorkersCellTableViewCell: UITableViewCell { 

    @IBOutlet weak var NameOfTheWorkerLabel: UILabel! 

    override func awakeFromNib() { 
     super.awakeFromNib() 
     // Initialization code 
    } 

    override func setSelected(selected: Bool, animated: Bool) { 
     super.setSelected(selected, animated: animated) 
     // Configure the view for the selected state 
    } 

} 
+2

Вы должны поставить некоторые имена в 'numOfWorkersNames'. Количество ячеек зависит от количества записей, которые у вас есть, и от вашего кода, который равен 0. –

+1

Идём учебник UITableView. –

ответ

0

Пожалуйста, укажите , что проблема и добавить, что данные в Tableview

If проблема в том, что при запуске приложения есть только пустой вид, вы должны добавить некоторые строки для numOfWorkersNames

, например: var numOfWorkersNames = ["worker1","worker2","worker3"]

затем numberOfRowsInSection получите счетчик массива, который является 3, и cellForRowAtIndexPath может получить его содержимое из массива numOfWorkdersNames

+0

Я не хочу создавать массив, который устанавливает некоторые предопределенные элементы. Имена рабочих будут добавлены в другое представление. С UITextField. – Army

+0

Так что просто добавьте некоторые данные в этот массив. Например: у вас есть текстовое поле и кнопка в другом месте. Когда вы нажмете кнопку, она добавит содержимое в текстовое поле к вашему рабочему массиву, поэтому в функции нажатия кнопки вы напишите 'numOfWorkersNames.append (textfield.text) tableView.reloadData()' – highsun16

+0

Спасибо за помощь. – Army

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