I have an String array like [1,2,3,4,5]. I am displaying this array in tableview. My Question is If I want to change the color of 3rd cell only, How can I compare 3rd element with array in ios swift?
on your tableview delegate method based on the condition change the color what you want
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = indexPath.row == 2 ? .red : yellow //or use cell.contentView.backgroundColor = = indexPath.row == 2 ? .red : yellow
}
if you want to change the array contains 3 condition based then use like
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = yourArrayName[indexPath.row] == "3" ? .red : yellow //or use cell.contentView.backgroundColor = = yourArrayName[indexPath.row] == "3" ? .red : yellow
}
okay we go with alternate way
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = .yellow
if let index = yourArrayName.index(of: "3") {
cell.backgroundColor = indexPath.row == index ? .red : yellow
}
}
You can check the condition inside your cellforrow function like this too :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ExampleCellIndentifier", for: indexPath) as! ExampleCell
if indexPath.row == 2{
// Do your modification on the 3rd cell item
cell.backgroundColor = .red
}
return cell
}
I just applied condition under cellForRowAt
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TextFieldInTableViewCell") as! myProfieTabelViewCellTableViewCell
if indexPath[1] % 2 == 0{
cell.backgroundColor = #colorLiteral(red: 0.9088078997, green: 0.9088078997, blue: 0.9088078997, alpha: 1)
print(indexPath[1])
}
else{
cell.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
}
cell.selectionStyle = .none
return cell
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.