According to the codes below, the first time I run the application.
The first 3 lines are working correctly.
But when I scroll up and down.
Some lines also change.
When I make a little more up and down
It changes to other lines
How can i solve this problem
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = KategoriEkleCell()
var KategoriId :String = ""
if tableView == tableView {
cell.selectionStyle = .none
cell = self.tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath as IndexPath) as! KategoriEkleCell
cell.itemLabel.text = (AltKategoriKayit[indexPath.section][indexPath.row] as? [String:String])?["kategoriadi"]
cell.itemLabel.font = UIFont(name:"OpenSans-Light", size: 14.0)
KategoriId = ((AltKategoriKayit[indexPath.section][indexPath.row] as? [String:String])?["kategoriid"])!
if (KategoriId) == (MenuKategoriKayit[indexPath.row]["kategoriid"]!) {
cell.EkleButton.layer.cornerRadius = 2
cell.EkleButton.layer.borderWidth = 1
cell.EkleButton.layer.borderColor = UIColor(red: 255/255, green: 56/255, blue: 107/255, alpha: 1.0).cgColor
cell.EkleButton.backgroundColor = UIColor(red: 255/255, green: 56/255, blue: 107/255, alpha: 1.0)
cell.EkleButton.setTitleColor(UIColor.white, for: .normal)
cell.EkleButton.clipsToBounds = true
}else {
cell.EkleButton.layer.cornerRadius = 2
cell.EkleButton.layer.borderWidth = 1
cell.EkleButton.layer.borderColor = UIColor(red: 255/255, green: 56/255, blue: 107/255, alpha: 1.0).cgColor
cell.EkleButton.clipsToBounds = true
}
}
return cell
}
Right employee
Faulty employee. when I scroll up and down.
As mentioned in the comments cells are reused.
You have to ensure that any UI element is set to a defined state in cellForRow. I moved the duplicate lines which both are executed in the if and else branch out of the if - else scope for better readability.
By the way the parentheses in the if line are not needed either
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let specialRed = UIColor(red: 1.0, green: 56/255, blue: 107/255, alpha: 1.0)
let cell = self.tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as! KategoriEkleCell
cell.selectionStyle = .none
cell.itemLabel.text = (AltKategoriKayit[indexPath.section][indexPath.row] as? [String:String])?["kategoriadi"]
cell.itemLabel.font = UIFont(name:"OpenSans-Light", size: 14.0)
let KategoriId = ((AltKategoriKayit[indexPath.section][indexPath.row] as? [String:String])?["kategoriid"])!
cell.EkleButton.layer.cornerRadius = 2
cell.EkleButton.layer.borderWidth = 1
cell.EkleButton.clipsToBounds = true
cell.EkleButton.layer.borderColor = specialRed.cgColor
if KategoriId == MenuKategoriKayit[indexPath.row]["kategoriid"]! {
cell.EkleButton.backgroundColor = specialRed
cell.EkleButton.setTitleColor(UIColor.white, for: .normal)
} else {
cell.EkleButton.backgroundColor = UIColor.white
cell.EkleButton.setTitleColor(specialRed, for: .normal)
}
return cell
}
Please consider that according to the naming convention variable names are supposed to start with a lowercase letter.
Related
I'm showing the data on tableview with multiple section,
when I open tableView height of section 1 should be 0. If I click a button in section 0 the height of the section 1 will be 150. For example if I click Agent button height of (want to) section cell show 150,I click builder button section hight will 0
I want to make the Section 1 visible on the button click from section 0
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! postaddTableViewCell1
cell.ownerButton.addTarget(self, action: #selector(FisrtButtonClick), for: .touchUpInside)
cell.agentButton.addTarget(self, action: #selector(FisrtButtonClick), for: .touchUpInside)
cell.builderButton.addTarget(self, action: #selector(FisrtButtonClick), for: .touchUpInside)
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as! postaddTableViewCell2
cell.checkbutton.tag = indexPath.row
cell.checkbutton.addTarget(self, action: #selector(checkbuttonClick) , for: .touchUpInside)
return cell
}
}
#objc func FisrtButtonClick(_ sender :UIButton)
{
let indexPath = IndexPath(row: 0, section: 0)
let cell = TableView.cellForRow(at: indexPath) as? postaddTableViewCell1
print(cell?.agentButton.titleLabel as Any)
if sender.tag == 10
{
cell?.ownerButton.backgroundColor = #colorLiteral(red: 0, green: 0.7254901961, blue: 0.4588235294, alpha: 1)
cell?.agentButton.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.768627451, blue: 0.768627451, alpha: 1)
cell?.builderButton.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.768627451, blue: 0.768627451, alpha: 1)
}else if sender.tag == 11
{
cell?.ownerButton.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.768627451, blue: 0.768627451, alpha: 1)
cell?.agentButton.backgroundColor = #colorLiteral(red: 0, green: 0.7254901961, blue: 0.4588235294, alpha: 1)
cell?.builderButton.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.768627451, blue: 0.768627451, alpha: 1)
} else if sender.tag == 12
{
cell?.ownerButton.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.768627451, blue: 0.768627451, alpha: 1)
cell?.agentButton.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.768627451, blue: 0.768627451, alpha: 1)
cell?.builderButton.backgroundColor = #colorLiteral(red: 0, green: 0.7254901961, blue: 0.4588235294, alpha: 1)
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0
{
return 80
}
if indexPath.section == 1
{
return 0
}
return 80
}
Check if the required button is clicked in the FisrtButtonClick method and set a boolean that is accessible to heightForRowAt. After toggling the boolean you can just reload the section you require (also cleaned up your code lil bit).
var selectedAgent = false
#objc func firstButtonClick(_ sender: UIButton) {
if sender.currentTitle == "Agent" {
selectedAgent = true
tableView.reloadSections([1], with: .automatic)
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 1 && !selectedAgent {
return 0
}
return 80
}
I have used a dequeueReusableCell in a list, and there are 4 UILabel in the cell. There are screenshots below.
Whichever the label has a prefix of "-", it will be Red, but after scroll it a few pages, the number has become a mess. Wonder if there a way to avoid this?
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RecipeTableCell", for: indexPath)
let currentRecipe = recipes?[indexPath.row]
let colorRed = UIColor(red: 0xFE/255, green: 0x38/255, blue: 0x24/255, alpha: 1) //FE3824
(cell.viewWithTag(100) as! UIImageView).image = UIImage(named: currentRecipe?.pic ?? "")
(cell.viewWithTag(200) as! UILabel).text = currentRecipe?.name
let hungryLabel = cell.viewWithTag(301) as! UILabel
hungryLabel.text = currentRecipe?.hungry_value
if (currentRecipe?.hungry_value!.hasPrefix("-"))! {
hungryLabel.textColor = colorRed
}
let healthLabel = (cell.viewWithTag(302) as! UILabel)
healthLabel.text = currentRecipe?.health_value
if (currentRecipe?.health_value!.hasPrefix("-"))! {
healthLabel.textColor = colorRed
}
let sanityLabel = (cell.viewWithTag(303) as! UILabel)
sanityLabel.text = currentRecipe?.sanity_value
if (currentRecipe?.sanity_value!.hasPrefix("-"))! {
sanityLabel.textColor = colorRed
}
(cell.viewWithTag(304) as! UILabel).text = currentRecipe?.duration
return cell
}
Thanks you guys.
I add a Black Color to 'else', it works, thank you
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RecipeTableCell", for: indexPath)
let currentRecipe = recipes?[indexPath.row]
let colorRed = UIColor(red: 0xFE/255, green: 0x38/255, blue: 0x24/255, alpha: 1) //FE3824
let colorBlack = UIColor(red: 74/255, green: 74/255, blue: 74/255, alpha: 1) //747474
(cell.viewWithTag(100) as! UIImageView).image = UIImage(named: currentRecipe?.pic ?? "")
(cell.viewWithTag(200) as! UILabel).text = currentRecipe?.name
let hungryLabel = cell.viewWithTag(301) as! UILabel
hungryLabel.text = currentRecipe?.hungry_value
if (currentRecipe?.hungry_value!.hasPrefix("-"))! {
hungryLabel.textColor = colorRed
} else {
hungryLabel.textColor = colorBlack
}
let healthLabel = (cell.viewWithTag(302) as! UILabel)
healthLabel.text = currentRecipe?.health_value
if (currentRecipe?.health_value!.hasPrefix("-"))! {
healthLabel.textColor = colorRed
} else {
healthLabel.textColor = colorBlack
}
let sanityLabel = (cell.viewWithTag(303) as! UILabel)
sanityLabel.text = currentRecipe?.sanity_value
if (currentRecipe?.sanity_value!.hasPrefix("-"))! {
sanityLabel.textColor = colorRed
} else {
sanityLabel.textColor = colorBlack
}
(cell.viewWithTag(304) as! UILabel).text = currentRecipe?.duration
return cell
}
in your cellForRowAt method you need to check if value is positive the color is black and if negative the it is red. For example
label.color = black
if negativeValue {
lagel.color = red
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PlaceCollectionViewCell
//let imageView = UIImageView()
//cell.backgroundColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00)
cell.layer.borderWidth = 0.5
cell.layer.borderColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00).cgColor
//cell.placeLabel.tintColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00).cgColor
cell.layer.cornerRadius = 40
cell.layer.masksToBounds = true
print("places\(indexPath.row)")
//cell.placeLabel.text = places[indexPath.row] as! String
cell.placeLabel.text = places[indexPath.row]
cell.placeLabel.textColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00)
// code for VIew
let view = UIView(frame: cell.bounds)
//Set background color that you want
view.backgroundColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00)
cell.selectedBackgroundView = view
return cell
I have an image in collection view cell. I need to display that image only when I click the cell.Do we have to do it in cellforRowat index path?
//Custom class code:
#IBOutlet weak var tickImageView: UIImageView!
#IBOutlet weak var placeViewBtn: UIButton!
#IBOutlet weak var placeLabel: UILabel!
#IBOutlet weak var imageView: UIImageView!
override func layoutSubviews() {
}
override func awakeFromNib() {
self.imageView.layer.cornerRadius = self.imageView.frame.size.width/2
self.imageView.layer.masksToBounds = true
super.awakeFromNib()
// Initialization code
}
Custom class code added. I want to display the ticMark image which I have declared above.
Declare one instance of type IndexPath and maintain the cell status is it selected or not with it. Now use this array within cellForItemAt indexPath and didSelectItemAt indexPath like this.
var selectedIndexPaths = IndexPath()
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PlaceCollectionViewCell
//Your code
//decide weather to show tick image or not
self.tickImageView.isHidden = self.selectedIndexPaths != indexPath
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if self.selectedIndexPaths == indexPath {
self.selectedIndexPaths = IndexPath()
}
else {
self.selectedIndexPaths = indexPath
}
self.tableview.reloadData()
}
You need to read wether the tick is selected or not in cellForRow
if tick is selected {
showImage
} else {
hideImage
}
Then in didSelectRow
set the tick to selected or deselected
then call reloadRowForIndexPath
I am trying to get the data from the selected rows in my tableView inside an array. I will append the selected row to the array and this does work great. Unfortunately when I deselect the row and select it again it will append it again. I need to write some logic to delete the deselected row from the array.
Does anyone know how I can do this?
Here is the code when I select a row:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath) as? exerciseCell
selectedCell?.contentView.backgroundColor = UIColor(red: 84.0 / 255, green: 199.0 / 255, blue: 252.0 / 255, alpha: 1)
rowSelected+=1
if rowSelected >= 1 {
nextBtn.isEnabled = true
nextBtn.backgroundColor = UIColor(red: 84.0 / 255, green: 199.0 / 255, blue: 252.0 / 255, alpha: 1)
}
let exercisesSelected = selectedCell?.exerciseNameLbl.text
exerisenames.append(exercisesSelected!)
print(exerisenames)
}
Here is the code for deselecting a row:
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath) as? exerciseCell
selectedCell?.textLabel?.textColor = UIColor.darkGray
rowSelected-=1
if rowSelected == 0 {
nextBtn.isEnabled = false
nextBtn.backgroundColor = UIColor.darkGray
nextBtn.setTitle("Choose an exercise", for: UIControlState.disabled)
}
let exercisesDeselected = selectedCell?.exerciseNameLbl.text
if exerisenames.contains(exercisesDeselected!) {
print("exercise already in the row and has to be deleted before going further")
}
print(exerisenames)
}
Both will refer to an array that I created in the top called: exercisenames
From a quick look at the docs, you probably want something like
if let index = exercisenames.index(of: exercisesDeselected) {
exercisenames.remove(at: index)
}
But I also think that #almas's suggestion of an ordered set might be good.
I have a tableview inside a viewcontroller. I have a little function to select all rows in the tableview. When I first display the viewcontroller and hit the select all button the function does not work. However, if I firstly select a row and then press the select all button, the function works as it should and all rows are selected. I'm not sure why this is happening. The tableview's delegate and data source have been set up in the storyboard.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:myTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! myTableViewCell
cell.accessoryType = .None
if allJobsSelected {
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.contentView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.selectedBackgroundView = bgColorView
cell.accessoryType = .Checkmark
cell.highlighted = false
cell.selected = true
// cell.accessoryType = .Checkmark
self.tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.None)
self.tableView(self.tableView, didSelectRowAtIndexPath: indexPath)
}
var job: Jobs!
job = jobs[UInt(indexPath.row)] as! Jobs
cell.reports2JobTitle.text = job.jobTitle
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.allowsMultipleSelection = true
if let cell:myTableViewCell = tableView.cellForRowAtIndexPath(indexPath) as? myTableViewCell {
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.contentView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.selectedBackgroundView = bgColorView
cell.accessoryType = .Checkmark
cell.highlighted = false
self.tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.Bottom)
}
}
#IBAction func doSelectAll(sender: UIBarButtonItem) {
let totalRows = tableView.numberOfRowsInSection(0)
for row in 0..<totalRows {
tableView.selectRowAtIndexPath(NSIndexPath(forRow: row, inSection: 0), animated: false, scrollPosition: UITableViewScrollPosition.None)
}
}
It would probably be a good idea to move this line:
self.tableView.allowsMultipleSelection = true
to your viewDidLoad
You are not guaranteed that the didSelect is called immediately -- it might be that each select is turning off the previous one and then a single didSelect is being called on the last row.