개발/iOS

swift UITableView 예제

도래울 2016. 4. 21. 11:33

In Swift there are no separate header and implementation files, the whole View Controller class is defined in the ViewController.swift file. Go to this file and right after the class ViewController: UIViewController {  line add a constant containing some data for the table rows.

let tableData = ["One","Two",Three"]

Swift has inferred the constant as an Array of Strings. Next, set the number of rows in the tableView:numberOfRowsInSection function. Add this function before the closing bracket of the class.

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int 
{    
  return self.tableData.count;
}

Our Table View will have 3 rows according to the count method of the Array class. Note in Swift a class method is called using the dot syntax. Next, implement the tableView:cellForRowAtIndexPath function

func tableView(tableView: UITableView!,
        cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{   
    let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"cell")      
    cell.textLabel?.text = tableData[indexPath.row]
                
    return cell 
}