user3745888
user3745888

Reputation: 6353

How to add a switch in cell of tableView in Swift?

I want add a switch in my cell into a tableView, but I don't know.. If I add this to storyboard an declared the outlet I get a error of connection. I only can add a ImageView with the parameter cell.imageView with this code but I can't add a switch.. how can make this?

  override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
    var cell:UITableViewCell! = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell!

    cell.textLabel.text = self.contacts[indexPath.row]
    cell.imageView.image = UIImage(named: "image")
    cell.imageView.layer.borderWidth=1.0
    cell.imageView.layer.masksToBounds = false
    cell.imageView.layer.cornerRadius = 13
    cell.imageView.clipsToBounds = true

        cell.backgroundColor = UIColor.clearColor()

    return cell
}

Thanks!

Upvotes: 2

Views: 3583

Answers (2)

Ben Kane
Ben Kane

Reputation: 10070

You're using the default UITableViewCell, which has set components in it. You'll need to:

  1. subclass UITableViewCell
  2. Go to the storyboard
  3. Set your cell style to custom in the attributes inspector
  4. Set the class to your custom class in the identity inspector
  5. dequeueReusableCellWithIdentifier as your custom class

With the cell style set to custom, you can add the switch and anything else you need right in the storyboard and hook up any IBOutlets and IBActions to your UITableViewCell subclass.

Upvotes: 1

Wain
Wain

Reputation: 119041

Because you are using a standard table view cell class

var cell:UITableViewCell! ...  as UITableViewCell!`

so you only have access to defined properties on that class. You should either be using a specific class so you have a property to access or accessing the subview in some other way (like by tag lookup, but note that the specific cell subclass is a better approach).

Upvotes: 0

Related Questions