Swift Tableview Cell Set Accessory Type

UITableViewCell Accessory Type Checked on Tap & Set other unchecked

I would keep track of the data that should be checked and change the cell in tableView:didSelectRowAtIndexPath: and update which data is checked in tableView:cellForRowAtIndexPath: like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// do usual stuff here including getting the cell

// determine the data from the IndexPath.row

if (data == self.checkedData)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}

return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// determine the selected data from the IndexPath.row

if (data != self.checkedData) {
self.checkedData = data;
}

[tableView reloadData];
}

How do i set cell.accessoryType to an image?

You can add your own image with the help of accessoryView of table view cell as below.

let cell = tableView.cellForRow(at: indexPath)    
let imgView = UIImageView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
imgView.image = UIImage(named: "{your image name}")!
cell.accessoryView = imgView

swift update cell accessory type

Storing the reference to the cell isn't a valid strategy as cells can be re-used when the table scrolls. You can't use the current cell accessory to indicate selection state for the same reason.

You can use an NSIndexSet or a Swift dictionary. Here is an implementation using a dictionary -

var selectedCells :Dictionary<String,PFUser>()

var friends: [PFUser] = []

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

let selectedCell = tableView.cellForRowAtIndexPath(indexPath) as FriendTableViewCell

let objectId=friends[indexPath.row].objectId

if (selectedCells[objectId] != nil){
selectedCell.accessoryType = .None
selectedCells.removeValueForKey(objectId)
} else
selectedCell.accessoryType = .Checkmark
selectedCells[objectId]=friends[indexPath.row]
}

tableView.deselectRowAtIndexPath(indexPath, animated:false)

}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("friend") as? FriendTableViewCell ?? FriendTableViewCell()
var round = 0
var friend: AnyObject = self.friends[indexPath.row]

cell.firstNameLabel.text = friend["firstName"] as? String

cell.lastNameLabel.text = friend["lastName"] as? String

if (selectedCells[friend.objectId] != nil){
selectedCell.accessoryType = .Checkmark
} else
selectedCell.accessoryType = .None
}

cell.firstNameLabel.sizeToFit()
cell.lastNameLabel.sizeToFit()
return cell
}


Related Topics



Leave a reply



Submit