Swift 3: Removing Duplicates / group them as 1 in uitableviewcell - ios

I am trying to either remove the duplicate entries fetched from the external database /group them as one. Initially, my sql query had a group clause. When I used it as group clause, the query was working, but not appropriately. I then removed the group clause from the query, it now shows the duplicate entries.
I have four regions: - North, East, South,West and ALL
By default it shows all region. Now there could be a profile that appears in more than one region. So when it loads as default - all regions, the profile should only appear once there, but when we tab on the regions, the profile should also show up there if the profile belongs in that region.
At them moment, it is showing all random. Some profiles that are available in more than one region, they do appear and some they dont. Some profile that is meant to be only in one region, do appear in 2 regions.
I dont know how can I share the code or screenshots, but happy to provide more details to look at the call.
Thanks
My code:
func removeDuplicate (sourceArray: [String]) -> [String] {
var uniqueArray:[String] = []
for object in sourceArray {
if !uniqueArray.contains(object)
{
uniqueArray.append(object)
}
}
return uniqueArray
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0
{
let cell = self.bussinessTableView.dequeueReusableCell(withIdentifier: "bussinessCell", for: indexPath) as! BussinessCell
let tableObjects:StorageSubCatagoriezTwo = subCatagorizeDataTwo[indexPath.row]
let testing = removeDuplicate(sourceArray: [tableObjects.nameString])
print(testing.description)
//let charCheck = (tableObjects.address).replacingOccurrences(of: " ", with: "")
if reg == "North"
{
cell.bussinessName.text = " "
cell.addLabel.text = " "
cell.telLabel.text = " "
cell.emailLabel.text = " "
cell.webLabel.text = " "
let tableObjects:StorageSubCatagoriezTwoNorth = subCatagorizeDataTwoN[indexPath.row]
if tableObjects.address.characters.isEmpty != true
{
cell.addLabel.text = tableObjects.address
}
else
{
//nothing
}
if tableObjects.telephone.characters.isEmpty != true
{
cell.telLabel.text = tableObjects.telephone
}
else
{
}
if tableObjects.email.characters.isEmpty != true
{
cell.emailLabel.text = tableObjects.email
}
else
{
}
if tableObjects.website.characters.isEmpty != true{
cell.webLabel.text = tableObjects.website
}
else{
}
}
else if reg == "East"
{
cell.bussinessName.text = " "
let tableObjects:StorageSubCatagoriezTwoEast = subCatagorizeDataTwoE[indexPath.row]
cell.bussinessName.text = tableObjects.nameString
if tableObjects.address.characters.isEmpty != true
{
cell.addLabel.text = tableObjects.address
}
else
{
//nothing
}
if tableObjects.telephone.characters.isEmpty != true
{
cell.telLabel.text = tableObjects.telephone
}
else
{
}
if tableObjects.email.characters.isEmpty != true
{
cell.emailLabel.text = tableObjects.email
}
else
{
}
if tableObjects.website.characters.isEmpty != true
{
cell.webLabel.text = tableObjects.website
}
else{
}
}
else if reg == "South"
{
cell.bussinessName.text = " "
let tableObjects:StorageSubCatagoriezTwoSouth = subCatagorizeDataTwoS[indexPath.row]
cell.bussinessName.text = tableObjects.nameString
if tableObjects.address.characters.isEmpty != true
{
cell.addLabel.text = tableObjects.address
}
else
{
//nothing
}
if tableObjects.telephone.characters.isEmpty != true
{
cell.telLabel.text = tableObjects.telephone
}
else
{
}
if tableObjects.email.characters.isEmpty != true
{
cell.emailLabel.text = tableObjects.email
}
else
{
}
if tableObjects.website.characters.isEmpty != true{
cell.webLabel.text = tableObjects.website
}
else{
}
}
else if reg == "West"
{
cell.bussinessName.text = " "
let tableObjects:StorageSubCatagoriezTwoWest = subCatagorizeDataTwoW[indexPath.row]
cell.bussinessName.text = tableObjects.nameString
if tableObjects.address.characters.isEmpty != true
{
cell.addLabel.text = tableObjects.address
}
else
{
//nothing
}
if tableObjects.telephone.characters.isEmpty != true
{
cell.telLabel.text = tableObjects.telephone
}
else
{
}
if tableObjects.email.characters.isEmpty != true
{
cell.emailLabel.text = tableObjects.email
}
else
{
}
if tableObjects.website.characters.isEmpty != true{
cell.webLabel.text = tableObjects.website
}
}
else{
let tableObjects:StorageSubCatagoriezTwo = subCatagorizeDataTwo[indexPath.row]
cell.bussinessName.text = tableObjects.nameString
let charCheck = (tableObjects.address).replacingOccurrences(of: " ", with: "")
cell.bussinessName.text = tableObjects.nameString
cell.addLabel.text = tableObjects.address
cell.telLabel.text = tableObjects.telephone
cell.emailLabel.text = tableObjects.email
cell.webLabel.text = tableObjects.website
}
return cell
}
else if indexPath.section == 1
{
let cell = self.bussinessTableView.dequeueReusableCell(withIdentifier: "bussinessCell2")
cell?.textLabel?.textAlignment = .center
switch regId
{
case 0:
if subCatagorizeDataTwo.count != forAll
{
cell?.textLabel?.text = "Load More Data"
cell?.textLabel?.textColor = Color.whiteColor
cell?.backgroundColor = UIColor.darkGray
}else{
cell?.textLabel?.text = "No More Data Found"
cell?.textLabel?.textColor = UIColor.darkGray
cell?.backgroundColor = UIColor.gray
cell?.selectionStyle = UITableViewCellSelectionStyle.none
}
case 1:
if subCatagorizeDataTwoN.count != forN
{
cell?.textLabel?.text = "Load More Data"
cell?.textLabel?.textColor = Color.whiteColor
cell?.backgroundColor = UIColor.darkGray
}else{
cell?.textLabel?.text = "No More Data Found"
cell?.textLabel?.textColor = UIColor.darkGray
cell?.backgroundColor = UIColor.gray
cell?.selectionStyle = UITableViewCellSelectionStyle.none
}
case 2:
if subCatagorizeDataTwoE.count != forE
{
cell?.textLabel?.text = "Load More Data"
cell?.textLabel?.textColor = Color.whiteColor
cell?.backgroundColor = UIColor.darkGray
}else{
cell?.textLabel?.text = "No More Data Found"
cell?.textLabel?.textColor = UIColor.darkGray
cell?.backgroundColor = UIColor.gray
cell?.selectionStyle = UITableViewCellSelectionStyle.none
}
case 3:
if subCatagorizeDataTwoS.count != forS
{
cell?.textLabel?.text = "Load More Data"
cell?.textLabel?.textColor = Color.whiteColor
cell?.backgroundColor = UIColor.darkGray
}else{
cell?.textLabel?.text = "No More Data Found"
cell?.textLabel?.textColor = UIColor.darkGray
cell?.backgroundColor = UIColor.gray
cell?.selectionStyle = UITableViewCellSelectionStyle.none
}
case 4:
if subCatagorizeDataTwoW.count != forW
{
cell?.textLabel?.text = "Load More Data"
cell?.textLabel?.textColor = Color.whiteColor
cell?.backgroundColor = UIColor.darkGray
}else{
cell?.textLabel?.text = "No More Data Found"
cell?.textLabel?.textColor = UIColor.darkGray
cell?.backgroundColor = UIColor.gray
cell?.selectionStyle = UITableViewCellSelectionStyle.none
}
default:break
}
return cell!
}
else
{
let tableObjects:StorageSubCatagoriez3rd = SubCatagoriez3rd[indexPath.row]
let cell = self.bussinessTableView.dequeueReusableCell(withIdentifier: "bussinessCell3")
cell?.textLabel?.text = tableObjects.nameString
return cell!
}
}

As per my knowledge if you want to remove duplicate from array then use below logic with your datatype
func removeDublicate (sourceArray: [Int]) -> [Int] {
var uniqueArray:[Int] = []
for object in sourceArray {
if !uniqueArray.contains(object)
{
uniqueArray.append(object)
}
}
return uniqueArray
}
let testing = removeDublicate(sourceArray: [1,2,2,5,1,8,3,1,2,8,5])
print(testing)
OUTPUT
[1, 2, 5, 8, 3]
Replace this line
let tableObjects:StorageSubCatagoriezTwoNorth = subCatagorizeDataTwoN[indexPath.row]
With this
var tableObjects:StorageSubCatagoriezTwoNorth = subCatagorizeDataTwoN[indexPath.row]
tableObjects = removeDuplicate(sourceArray: [tableObjects.nameString ])
Do it for all regions

In swift 3 you can use this code for removing duplicate from array. Only this much code is needed. Try this code..
import UIKit
class ViewController2: UIViewController {
var myArray: [Int] = [1,2,3,4,3,2,5,7,5,8]
override func viewDidLoad()
{
super.viewDidLoad()
let uniqueArray = Array(Set(self.myArray))
print(uniqueArray) // This print result will be [2, 4, 5, 7, 1, 8]
}
}
OUTPUT
[2, 4, 5, 7, 1, 8]

Related

How to change multiple table height dynamically as per array data count

I have 3 array different array which is cricketMatchArray, soccerMatchArray and tennisMatchArray.I'm display these 3 array data in 3 tableview which is expanding after clicking on header.Now I'm facing an issue table height is not change according to array data.
This output is I'm getting and I want remove that red mark space
for e.g:
if cricket and tennis array having a data and soccer array is empty then soccer table height not changing
I want to change tables height dynamically asper array count.
for e.g
if cricket and tennis array having a data and soccer array is empty then soccer table height should be 0
Here is my code..
class AllLiveMatchesViewController: UIViewController {
#IBOutlet weak var cricketTableView: UITableView!
#IBOutlet weak var soccerTableView: UITableView!
#IBOutlet weak var tennisTableView: UITableView!
var selectedIndx = -1
var thereIsCellTapped = false
var cricketMatchArray = [LiveMatchesData]()
var soccerMatchArray = [LiveMatchesData]()
var tennisMatchArray = [LiveMatchesData]()
override func viewDidLoad() {
super.viewDidLoad()
cricketTableView.dataSource = self
cricketTableView.delegate = self
cricketTableView.separatorStyle = .none
cricketTableView.tableFooterView = UIView()
soccerTableView.dataSource = self
soccerTableView.delegate = self
soccerTableView.separatorStyle = .none
soccerTableView.tableFooterView = UIView()
tennisTableView.dataSource = self
tennisTableView.delegate = self
tennisTableView.separatorStyle = .none
tennisTableView.tableFooterView = UIView()
getCricketMatches()
getSoccerMatches()
getTennisMatches()
}
extension AllLiveMatchesViewController: UITableViewDelegate, UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
if tableView == cricketTableView
{
return cricketMatchArray.count
}
else if tableView == soccerTableView
{
return soccerMatchArray.count
}
else if tableView == tennisTableView
{
return tennisMatchArray.count
}
else
{
return 0
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == cricketTableView
{
return cricketMatchArray[section].score.count
}
else if tableView == soccerTableView
{
return soccerMatchArray[section].score.count
}
else if tableView == tennisTableView
{
return tennisMatchArray[section].score.count
}
else
{
return 0
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if tableView == cricketTableView
{
let obj = cricketMatchArray[section]
if cricketMatchArray.count == 0
{
return 0
}
else
{
if obj.inplay == true && obj.status == "OPEN"
{
return 50
}
else if obj.inplay == false && obj.status == "OPEN"
{
return 0
}
else
{
return 0
}
}
}
else if tableView == soccerTableView
{
let obj = soccerMatchArray[section]
if obj.inplay == true && obj.status == "OPEN"
{
return 50
}
else if obj.inplay == false && obj.status == "OPEN"
{
return 0
}
else
{
return 0
}
}
else if tableView == tennisTableView
{
let obj = tennisMatchArray[section]
if obj.inplay == true && obj.status == "OPEN"
{
return 50
}
else if obj.inplay == false && obj.status == "OPEN"
{
return 0
}
else
{
return 0
}
}
else
{
return 0
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if tableView == cricketTableView
{
if indexPath.section == selectedIndx && thereIsCellTapped{
return 106
}
else{
return 0
}
}
else if tableView == soccerTableView
{
if indexPath.section == selectedIndx && thereIsCellTapped{
return 106
}
else{
return 0
}
}
else if tableView == tennisTableView
{
if indexPath.section == selectedIndx && thereIsCellTapped{
return 106
}
else{
return 0
}
}
else
{
return 0
}
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if tableView == cricketTableView
{
if (self.selectedIndx != section) && thereIsCellTapped{
return 0
}
else if (self.selectedIndx == section) && thereIsCellTapped{
return 20
}
else
{
return 0
}
}
else if tableView == soccerTableView
{
if (self.selectedIndx != section) && thereIsCellTapped{
return 0
}
else if (self.selectedIndx == section) && thereIsCellTapped{
return 20
}
else
{
return 0
}
}
else if tableView == tennisTableView
{
if (self.selectedIndx != section) && thereIsCellTapped{
return 0
}
else if (self.selectedIndx == section) && thereIsCellTapped{
return 20
}
else
{
return 0
}
}
else
{
return 0
}
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: ExpandExtTableViewCell.self)) as! ExpandExtTableViewCell
if section == selectedIndx && thereIsCellTapped{
cell.footerView.roundCorners(corners: [.bottomLeft,.bottomRight], radius: 10)
}
else
{
cell.footerView.roundCorners(corners: [.bottomLeft,.bottomRight], radius: 0)
}
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if tableView == cricketTableView
{
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: ExpandTableViewCell.self)) as! ExpandTableViewCell
let obj = cricketMatchArray[section]
if obj.inplay == false && obj.status == "CLOSE"
{
cell.liveView.isHidden = true
}
else if obj.inplay == true && obj.status == "OPEN"
{
cell.liveView.isHidden = false
}
cell.sportIcon.image = UIImage(named: "whiteball")
cell.teamNameLabel.text = obj.name ?? ""
cell.btnSelection.tag = section
cell.btnSelection.addTarget(self, action: #selector(AllLiveMatchesViewController.btnSectionClick(sender:)), for: .touchUpInside)
if section == selectedIndx && thereIsCellTapped{
cell.headerView.roundCorners(corners: [.topLeft,.topRight], radius: 10)
}
else
{
cell.headerView.roundCorners(corners: [.topLeft,.topRight,.bottomLeft,.bottomRight], radius: 10)
}
return cell
}
else if tableView == soccerTableView
{
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: SoccerExpandTableViewCell.self)) as! SoccerExpandTableViewCell
let obj = soccerMatchArray[section]
if obj.inplay == false && obj.status == "CLOSE"
{
cell.liveView.isHidden = true
}
else if obj.inplay == true && obj.status == "OPEN"
{
cell.liveView.isHidden = false
}
cell.sportIcon.image = UIImage(named: "soccerball")
cell.teamNameLabel.text = obj.name ?? ""
cell.btnSelection2.tag = section
cell.btnSelection2.addTarget(self, action: #selector(AllLiveMatchesViewController.btnSectionClick2(sender:)), for: .touchUpInside)
if section == selectedIndx && thereIsCellTapped{
cell.headerView.roundCorners(corners: [.topLeft,.topRight], radius: 10)
}
else
{
cell.headerView.roundCorners(corners: [.topLeft,.topRight,.bottomLeft,.bottomRight], radius: 10)
}
return cell
}
else if tableView == tennisTableView
{
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: TennisExpandTableViewCell.self)) as! TennisExpandTableViewCell
let obj = tennisMatchArray[section]
if obj.inplay == false && obj.status == "CLOSE"
{
cell.liveView.isHidden = true
}
else if obj.inplay == true && obj.status == "OPEN"
{
cell.liveView.isHidden = false
}
cell.sportIcon.image = UIImage(named: "tennisracket")
cell.teamNameLabel.text = obj.name ?? ""
cell.btnSelection3.tag = section
cell.btnSelection3.addTarget(self, action: #selector(AllLiveMatchesViewController.btnSectionClick3(sender:)), for: .touchUpInside)
if section == selectedIndx && thereIsCellTapped{
cell.headerView.roundCorners(corners: [.topLeft,.topRight], radius: 10)
}
else
{
cell.headerView.roundCorners(corners: [.topLeft,.topRight,.bottomLeft,.bottomRight], radius: 10)
}
return cell
}
else
{
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: ExpandTableViewCell.self)) as! ExpandTableViewCell
return cell
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: ExpandInsideTableViewCell.self)) as! ExpandInsideTableViewCell
if tableView == cricketTableView
{
let ob = cricketMatchArray[indexPath.section]
let obj = cricketMatchArray[indexPath.section].score[indexPath.row]
if obj.spnnation1 == nil
{
let teamName = ob.name?.components(separatedBy: " v ")
let fTeamWords = teamName?[0].split { !$0.isLetter }
let sTeamWords = teamName?[1].split { !$0.isLetter }
if fTeamWords?.count == 1
{
let fTeam = teamName?[0].prefix(3)
cell.firstTeamName.text = fTeam?.description.uppercased()
}
else
{
let fTeam = teamName?[0].getAcronyms()
cell.firstTeamName.text = fTeam
}
if sTeamWords?.count == 1
{
let fTeam = teamName?[1].prefix(3)
cell.secondTeamName.text = fTeam?.description.uppercased()
}
else
{
let fTeam = teamName?[1].getAcronyms()
cell.secondTeamName.text = fTeam
}
cell.firstTeamScore.text = obj.score1
cell.secondTeamScore.text = obj.score2
cell.dateLabel.text = ob.openDate
cell.commonScore.isHidden = true
}
else
{
cell.firstTeamName.text = obj.spnnation1
cell.secondTeamName.text = obj.spnnation2
cell.firstTeamScore.text = obj.score1
cell.secondTeamScore.text = obj.score2
cell.dateLabel.text = ob.openDate
cell.commonScore.isHidden = true
}
}
else if tableView == soccerTableView
{
let ob = soccerMatchArray[indexPath.section]
let obj = soccerMatchArray[indexPath.section].score[indexPath.row]
if obj.spnnation1 == nil
{
let teamName = ob.name?.components(separatedBy: " v ")
let fTeamWords = teamName?[0].split { !$0.isLetter }
let sTeamWords = teamName?[1].split { !$0.isLetter }
if fTeamWords?.count == 1
{
let fTeam = teamName?[0].prefix(3)
cell.firstTeamScore.text = fTeam?.description.uppercased()
}
else
{
let fTeam = teamName?[0].getAcronyms()
cell.firstTeamScore.text = fTeam
}
if sTeamWords?.count == 1
{
let fTeam = teamName?[1].prefix(3)
cell.secondTeamScore.text = fTeam?.description.uppercased()
}
else
{
let fTeam = teamName?[1].getAcronyms()
cell.secondTeamScore.text = fTeam
}
cell.firstTeamName.isHidden = true
cell.secondTeamName.isHidden = true
cell.dateLabel.text = ob.openDate
cell.commonScore.isHidden = false
cell.commonScore.text = "\(obj.score1 ?? "")-\(obj.score2 ?? "")"
}
else
{
cell.firstTeamName.isHidden = true
cell.secondTeamName.isHidden = true
cell.firstTeamScore.text = obj.spnnation1?.getAcronyms()
cell.secondTeamScore.text = obj.spnnation2?.getAcronyms()
cell.dateLabel.text = ob.openDate
cell.commonScore.isHidden = false
cell.commonScore.text = "\(obj.score1 ?? "")-\(obj.score2 ?? "")"
}
}
else if tableView == tennisTableView
{
let ob = tennisMatchArray[indexPath.section]
let obj = tennisMatchArray[indexPath.section].score[indexPath.row]
if obj.spnnation1 == nil
{
let teamName = ob.name?.components(separatedBy: " v ")
let fTeamWords = teamName?[0].split { !$0.isLetter }
let sTeamWords = teamName?[1].split { !$0.isLetter }
if fTeamWords?.count == 1
{
let fTeam = teamName?[0].prefix(3)
cell.firstTeamScore.text = fTeam?.description.uppercased()
}
else
{
let fTeam = teamName?[0].getAcronyms()
cell.firstTeamScore.text = fTeam
}
if sTeamWords?.count == 1
{
let fTeam = teamName?[1].prefix(3)
cell.secondTeamScore.text = fTeam?.description.uppercased()
}
else
{
let fTeam = teamName?[1].getAcronyms()
cell.secondTeamScore.text = fTeam
}
cell.firstTeamName.isHidden = true
cell.secondTeamName.isHidden = true
cell.dateLabel.text = ob.openDate
cell.commonScore.isHidden = false
cell.commonScore.text = "\(obj.score1 ?? "")-\(obj.score2 ?? "")"
}
else
{
cell.firstTeamName.isHidden = true
cell.secondTeamName.isHidden = true
cell.firstTeamScore.text = obj.spnnation1?.getAcronyms()
cell.secondTeamScore.text = obj.spnnation2?.getAcronyms()
cell.dateLabel.text = ob.openDate
cell.commonScore.isHidden = false
cell.commonScore.text = "\(obj.score1 ?? "")-\(obj.score2 ?? "")"
}
}
return cell
}
Can someone help me out with this.
The problem is that you duplicate code but not properties :
if tableView == cricketTableView
{
// This is the problem :
// only one selectedIndx and one thereIsCellTapped but 3 tables, so it give the same result
// for the 3 tables
if (self.selectedIndx != section) && thereIsCellTapped{
return 0
}
else if (self.selectedIndx == section) && thereIsCellTapped{
return 20
}
else
{
return 0
}
}
You have this problem in :
heightForRowAt
heightForFooterInSection
viewForFooterInSection
viewForHeaderInSection
and may in didSelectRowAt
As a curiosity question - why do you have 3 separate tableviews instead of one with sections?
Having 3 different UITableViews in one ViewController is in this case - not needed.
By controlling number of cells in section we can simplify the logic of the view later on.
Tapping on the header should control the logic of "hiding" (= setting number of rows in given section to zero) of other sections.
You can use Single TableView with a cell having StackView in it by giving it Top, Leading, Trailing, Bottom.
Your number of rows in section should be 3. It means you have three cells in it now populate your arrays in each cell.
Your heightForRowAt should be UITableView.automaticDimension

UIStackViews are collapsing inside of another UIStackView and TableView

Pretty new to this so I appreciate any and all help here.
I've spent a lot of time perusing the web and trying different solutions but I'm at a loss.
I'm using tableView to populate events within a view. These events can have multiple participants (2 - 8) The participants (and other objects) are represented by sub-stackviews and I control whether or not to display stackView7, stackView8, etc. based on the count of an array of participants.
For some reason, sometimes, one or a few of the participant stackViews is being crushed to a smaller size.
I'm sorry there's so much code attached but I'm really not sure what will be relevant.
Thank you in advance and let me know if different code is needed for context
Image with error
Image as it should be
Example of stackView layout
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "challengeCell", for: indexPath)
let participant1Photo = cell.viewWithTag(10) as! UIImageView
let participant1Name = cell.viewWithTag(11) as! UILabel
let participant2Photo = cell.viewWithTag(20) as! UIImageView
let participant2Name = cell.viewWithTag(21) as! UILabel
let participant3Stack = cell.viewWithTag(3)
let participant3Photo = cell.viewWithTag(30) as! UIImageView
let participant3Name = cell.viewWithTag(31) as! UILabel
let participant4Stack = cell.viewWithTag(4)
let participant4Photo = cell.viewWithTag(40) as! UIImageView
let participant4Name = cell.viewWithTag(41) as! UILabel
let participant5Stack = cell.viewWithTag(5)
let participant5Photo = cell.viewWithTag(50) as! UIImageView
let participant5Name = cell.viewWithTag(51) as! UILabel
let participant6Stack = cell.viewWithTag(6)
let participant6Photo = cell.viewWithTag(60) as! UIImageView
let participant6Name = cell.viewWithTag(61) as! UILabel
let participant7Stack = cell.viewWithTag(7)
let participant7Photo = cell.viewWithTag(70) as! UIImageView
let participant7Name = cell.viewWithTag(71) as! UILabel
let participant8Stack = cell.viewWithTag(8)
let participant8Photo = cell.viewWithTag(80) as! UIImageView
let participant8Name = cell.viewWithTag(81) as! UILabel
//set up stacks
participant3Stack?.isHidden = true
participant4Stack?.isHidden = true
participant5Stack?.isHidden = true
participant6Stack?.isHidden = true
participant7Stack?.isHidden = true
participant8Stack?.isHidden = true
//MARK: participant1
if challenges[indexPath.row].confirmed?.contains(challenges[indexPath.row].participants![0]) == true {
participant1Accepted.image = UIImage(systemName: "person.fill.checkmark")
participant1Accepted.tintColor = UIColor.systemGreen
} else if challenges[indexPath.row].denied?.contains(challenges[indexPath.row].participants![0]) == true {
participant1Accepted.image = UIImage(systemName: "person.fill.xmark")
participant1Accepted.tintColor = UIColor.systemRed
}
if currUserID == challenges[indexPath.row].participants![0] {
participant1Name.text = "You"
} else {
participant1Name.text = challenges[indexPath.row].senderUserName
}
UserActivityService.getUserActivity(userActivityID: String(challenges[indexPath.row].senderUserID! + challenges[indexPath.row].activity!)) { (userActivity) in
participant1Average.text = String((userActivity?.averageScore)!)
participant1Best.text = String((userActivity?.bestScore)!)
if (userActivity?.played)! < 1 {
participant1Win.text = "0%"
} else {
participant1Win.text = String("\((((userActivity?.wins)! / (userActivity?.played)!) * 1000).rounded() / 10)%")
}
}
//MARK: participant2
if challenges[indexPath.row].confirmed?.contains(challenges[indexPath.row].participants![1]) == true {
participant2Accepted.image = UIImage(systemName: "person.fill.checkmark")
participant2Accepted.tintColor = UIColor.systemGreen
} else if challenges[indexPath.row].denied?.contains(challenges[indexPath.row].participants![1]) == true {
participant2Accepted.image = UIImage(systemName: "person.fill.xmark")
participant2Accepted.tintColor = UIColor.systemRed
}
if currUserID == challenges[indexPath.row].participants![1] {
participant2Name.text = "You"
} else {
participant2Name.text = challenges[indexPath.row].receiverUserName
}
UserActivityService.getUserActivity(userActivityID: String(challenges[indexPath.row].receiverUserID! + challenges[indexPath.row].activity!)) { (userActivity) in
participant2Average.text = String((userActivity?.averageScore)!)
participant2Best.text = String((userActivity?.bestScore)!)
if (userActivity?.played)! < 1 {
participant2Win.text = "0%"
} else {
participant2Win.text = String("\((((userActivity?.wins)! / (userActivity?.played)!) * 1000).rounded() / 10)%")
}
}
//MARK: participant3
if challenges[indexPath.row].participants!.count > 2 {
if currUserID == challenges[indexPath.row].participants![2] {
participant3Name.text = "You"
} else {
UserService.getUserName(userID: challenges[indexPath.row].participants![2]) { (userNameData) in
participant3Name.text = userNameData
}
}
if challenges[indexPath.row].confirmed?.contains(challenges[indexPath.row].participants![2]) == true {
participant3Accepted.image = UIImage(systemName: "person.fill.checkmark")
participant3Accepted.tintColor = UIColor.systemGreen
} else if challenges[indexPath.row].denied?.contains(challenges[indexPath.row].participants![2]) == true {
participant3Accepted.image = UIImage(systemName: "person.fill.xmark")
participant3Accepted.tintColor = UIColor.systemRed
}
participant3Stack?.isHidden = false
UserActivityService.getUserActivity(userActivityID: String(challenges[indexPath.row].participants![2] + challenges[indexPath.row].activity!)) { (userActivity) in
participant3Average.text = String((userActivity?.averageScore)!)
participant3Best.text = String((userActivity?.bestScore)!)
if (userActivity?.played)! < 1 {
participant3Win.text = "0%"
} else {
participant3Win.text = String("\((((userActivity?.wins)! / (userActivity?.played)!) * 1000).rounded() / 10)%")
}
}
//MARK: participant4
if challenges[indexPath.row].participants!.count > 3 {
if currUserID == challenges[indexPath.row].participants![3] {
participant4Name.text = "You"
} else {
UserService.getUserName(userID: challenges[indexPath.row].participants![3]) { (userNameData) in
participant4Name.text = userNameData
}
}
if challenges[indexPath.row].confirmed?.contains(challenges[indexPath.row].participants![3]) == true {
participant4Accepted.image = UIImage(systemName: "person.fill.checkmark")
participant4Accepted.tintColor = UIColor.systemGreen
} else if challenges[indexPath.row].denied?.contains(challenges[indexPath.row].participants![3]) == true {
participant4Accepted.image = UIImage(systemName: "person.fill.xmark")
participant4Accepted.tintColor = UIColor.systemRed
}
participant4Stack?.isHidden = false
UserActivityService.getUserActivity(userActivityID: String(challenges[indexPath.row].participants![3] + challenges[indexPath.row].activity!)) { (userActivity) in
participant4Average.text = String((userActivity?.averageScore)!)
participant4Best.text = String((userActivity?.bestScore)!)
if (userActivity?.played)! < 1 {
participant4Win.text = "0%"
} else {
participant4Win.text = String("\((((userActivity?.wins)! / (userActivity?.played)!) * 1000).rounded() / 10)%")
}
}
//MARK: participant5
if challenges[indexPath.row].participants!.count > 4 {
if currUserID == challenges[indexPath.row].participants![4] {
participant5Name.text = "You"
} else {
UserService.getUserName(userID: challenges[indexPath.row].participants![4]) { (userNameData) in
participant5Name.text = userNameData
}
}
if challenges[indexPath.row].confirmed?.contains(challenges[indexPath.row].participants![4]) == true {
participant5Accepted.image = UIImage(systemName: "person.fill.checkmark")
participant5Accepted.tintColor = UIColor.systemGreen
} else if challenges[indexPath.row].denied?.contains(challenges[indexPath.row].participants![4]) == true {
participant5Accepted.image = UIImage(systemName: "person.fill.xmark")
participant5Accepted.tintColor = UIColor.systemRed
}
participant5Stack?.isHidden = false
UserActivityService.getUserActivity(userActivityID: String(challenges[indexPath.row].participants![4] + challenges[indexPath.row].activity!)) { (userActivity) in
participant5Average.text = String((userActivity?.averageScore)!)
participant5Best.text = String((userActivity?.bestScore)!)
if (userActivity?.played)! < 1 {
participant5Win.text = "0%"
} else {
participant5Win.text = String("\((((userActivity?.wins)! / (userActivity?.played)!) * 1000).rounded() / 10)%")
}
}
//MARK: participant6
if challenges[indexPath.row].participants!.count > 5 {
if currUserID == challenges[indexPath.row].participants![5] {
participant6Name.text = "You"
} else {
UserService.getUserName(userID: challenges[indexPath.row].participants![5]) { (userNameData) in
participant6Name.text = userNameData
}
}
if challenges[indexPath.row].confirmed?.contains(challenges[indexPath.row].participants![5]) == true {
participant6Accepted.image = UIImage(systemName: "person.fill.checkmark")
participant6Accepted.tintColor = UIColor.systemGreen
} else if challenges[indexPath.row].denied?.contains(challenges[indexPath.row].participants![5]) == true {
participant6Accepted.image = UIImage(systemName: "person.fill.xmark")
participant6Accepted.tintColor = UIColor.systemRed
}
participant6Stack?.isHidden = false
UserActivityService.getUserActivity(userActivityID: String(challenges[indexPath.row].participants![5] + challenges[indexPath.row].activity!)) { (userActivity) in
participant6Average.text = String((userActivity?.averageScore)!)
participant6Best.text = String((userActivity?.bestScore)!)
if (userActivity?.played)! < 1 {
participant6Win.text = "0%"
} else {
participant6Win.text = String("\((((userActivity?.wins)! / (userActivity?.played)!) * 1000).rounded() / 10)%")
}
}
//MARK: participant7
if challenges[indexPath.row].participants!.count > 6 {
if currUserID == challenges[indexPath.row].participants![6] {
participant7Name.text = "You"
} else {
UserService.getUserName(userID: challenges[indexPath.row].participants![6]) { (userNameData) in
participant7Name.text = userNameData
}
}
if challenges[indexPath.row].confirmed?.contains(challenges[indexPath.row].participants![6]) == true {
participant7Accepted.image = UIImage(systemName: "person.fill.checkmark")
participant7Accepted.tintColor = UIColor.systemGreen
} else if challenges[indexPath.row].denied?.contains(challenges[indexPath.row].participants![6]) == true {
participant7Accepted.image = UIImage(systemName: "person.fill.xmark")
participant7Accepted.tintColor = UIColor.systemRed
}
participant7Stack?.isHidden = false
UserActivityService.getUserActivity(userActivityID: String(challenges[indexPath.row].participants![6] + challenges[indexPath.row].activity!)) { (userActivity) in
participant7Average.text = String((userActivity?.averageScore)!)
participant7Best.text = String((userActivity?.bestScore)!)
if (userActivity?.played)! < 1 {
participant7Win.text = "0%"
} else {
participant7Win.text = String("\((((userActivity?.wins)! / (userActivity?.played)!) * 1000).rounded() / 10)%")
}
}
//MARK: participant8
if challenges[indexPath.row].participants!.count > 7 {
if currUserID == challenges[indexPath.row].participants![7] {
participant8Name.text = "You"
} else {
UserService.getUserName(userID: challenges[indexPath.row].participants![7]) { (userNameData) in
participant8Name.text = userNameData
}
}
if challenges[indexPath.row].confirmed?.contains(challenges[indexPath.row].participants![7]) == true {
participant8Accepted.image = UIImage(systemName: "person.fill.checkmark")
participant8Accepted.tintColor = UIColor.systemGreen
} else if challenges[indexPath.row].denied?.contains(challenges[indexPath.row].participants![7]) == true {
participant8Accepted.image = UIImage(systemName: "person.fill.xmark")
participant8Accepted.tintColor = UIColor.systemRed
}
participant8Stack?.isHidden = false
UserActivityService.getUserActivity(userActivityID: String(challenges[indexPath.row].participants![7] + challenges[indexPath.row].activity!)) { (userActivity) in
participant8Average.text = String((userActivity?.averageScore)!)
participant8Best.text = String((userActivity?.bestScore)!)
if (userActivity?.played)! < 1 {
participant8Win.text = "0%"
} else {
participant8Win.text = String("\((((userActivity?.wins)! / (userActivity?.played)!) * 1000).rounded() / 10)%")
}
}
}
return cell
}
The problem was that subviews within the TableView cell were being resized by the system.
The solution was to set hugging priorities and compression resistance priorities on each of the stack views that were affected. This prevented any system resizing that was occurring.

How can I update my datasource and animate the changes with RxSwift in my tableview?

Datasource is updating, but the changes are not being displayed in the Tableview.
I am experimenting with Friends, Users, & Users Request tableview with 3 sections. When a user has a request from a user, he or she appears under the request section. However, when the user clicks "accept" the console is reading it's hitting the firebase server, but the changes that that request was actually made is not registering and the request remains in the section until you reload the view. I have tried forcing a tableview to reload, but to no avail.
struct SectionOfuserRxx {
var header: String
var items: [Item]
}
extension SectionOfuserRxx: IdentifiableType {
}
extension SectionOfuserRxx: AnimatableSectionModelType {
// typealias Item = user
typealias Identity = String
////
typealias Item = user
init(original: SectionOfuserRxx, items: [Item]) {
self = original
self.items = items
}
var identity: String {
return header
}
}
// Above viewDidLoad
let disposeBag = DisposeBag()
//
//Inside viewDidLoad
let dataSource = RxTableViewSectionedAnimatedDataSource<SectionOfuserRxx>(
configureCell: { dataSource, tableView, indexPath, item in
switch (indexPath.section) {
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath) as? userCell
let userProfileImageURLFirebaseReturn = item.userImageURL
let userNameTagFirebaseReturn = item.nametag
let userNameFirebaseReturn = item.username
let imageURL = userProfileImageURLFirebaseReturn
let resource = ImageResource(downloadURL: URL(string: imageURL!)!, cacheKey: userProfileImageURLFirebaseReturn)
cell?.userProfileImage.kf.setImage(with: resource)
cell?.usernameLbl.text = userNameFirebaseReturn
cell?.userNameTagLbl.text = "| " + userNameTagFirebaseReturn!
cell!.setFunction {
cell!.button.isEnabled = true
let id = item.userUID
FriendSystem.system.sendRequestToUser(id!)
}
return cell!
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "friendsCell", for: indexPath) as? friendsCell
cell!.buttons.isEnabled = true
cell!.buttons.setTitle("Remove", for: UIControl.State())
// print("Friend Count: \(item.count)");
print(" INDEXING ROW FOR FRIENDS: \(indexPath.row)")
let userProfileImageURLFirebaseReturn = item.userImageURL ?? ""
let userNameTagFirebaseReturn = item.nametag ?? ""
let userNameFirebaseReturn = item.username ?? ""
let imageURL = userProfileImageURLFirebaseReturn
// self.urlContentArray.append(imageURL)
if imageURL != "" {
let resource = ImageResource(downloadURL: URL(string: imageURL)!, cacheKey: userProfileImageURLFirebaseReturn)
cell?.userProfileImage.kf.setImage(with: resource)
} else {
cell?.userProfileImage.image = UIImage(named: "heartfilled")
}
cell?.usernameLbl.text = userNameFirebaseReturn
cell?.userNameTagLbl.text = userNameTagFirebaseReturn;
cell!.setFunction {
cell!.buttons.isEnabled = true
let id = item.userUID
// FriendSystem.system.friendList.remove(at: indexPath.row)
FriendSystem.system.removeFriend(id!)
}
return cell!
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "requestCell", for: indexPath) as? requestCell
cell!.button.isEnabled = true
// cell!.button.setTitle("Accept", for: UIControl.State())
let userProfileImageURLFirebaseReturn = item.userImageURL
let userNameTagFirebaseReturn = item.nametag
let userNameFirebaseReturn = item.username
let imageURL = userProfileImageURLFirebaseReturn
// self.urlContentArray.append(imageURL)
// guard imageURL != nil && imageURL != "" else {return}
if imageURL != nil && userProfileImageURLFirebaseReturn != nil && userProfileImageURLFirebaseReturn != "" && imageURL != "" {
let resource = ImageResource(downloadURL: URL(string: imageURL!)!, cacheKey: userProfileImageURLFirebaseReturn)
cell?.userProfileImage.kf.setImage(with: resource)
cell?.usernameLbl.text = userNameFirebaseReturn
cell?.userNameTagLbl.text = userNameTagFirebaseReturn
};
// cell?.userProfileImage.kf.setImage(with: resource)
cell?.usernameLbl.text = userNameFirebaseReturn
cell?.userNameTagLbl.text = userNameTagFirebaseReturn
//cell?.button.backgroundColor = #colorLiteral(red: 1, green: 0.3354814752, blue: 0.289293822, alpha: 1)
cell!.setFunction {
cell!.button.isEnabled = true
let id = item.userUID
FriendSystem.system.acceptFriendRequest(id!)
}
return cell!
default:
return UITableViewCell();
}},
titleForHeaderInSection: { dataSource, index in
return dataSource.sectionModels[index].header
});
dataSource.animationConfiguration = AnimationConfiguration(insertAnimation: .fade, reloadAnimation: .fade, deleteAnimation: .fade);
******* THIS IS HOW THE ARRAY IS BEING UPDATED AND BEING PULLED IN WITH A FIREBASE OBSERVER IN THE VIEWDIDLOAD *******
var requestList = user
var requestListUser = [String]()
/** Adds a friend request observer. The completion function will run every time this list changes, allowing you
to update your UI. */
func addRequestObserver(_ update: #escaping () -> Void) {
let ref = USER_REF.child((Auth.auth().currentUser?.uid)!).child("requests");
ref.keepSynced(true);
ref.observe(DataEventType.value, with: { (snapshot) in
guard (Auth.auth().currentUser?.uid) != nil else { return }
self.requestList.removeAll()
self.requestListUser.removeAll()
for child in snapshot.children.allObjects as! [DataSnapshot] {
let id = child.key
FriendSystem.system.getCurrentUser({ (userDataReturned) in
if userDataReturned.email != nil && userDataReturned.userImageURL != nil &&
userDataReturned.nametag != nil &&
userDataReturned.username != nil &&
userDataReturned.userUID != nil {
self.requestListUser.append(id);
self.getUser(id, completion: { (user) in
self.requestList.append(user)
update()
});
} else {
print("User request account had an account not completely populated")
}
})
// self.requestListUser.append(id)
// self.getUser(id, completion: { (user) in
// self.requestList.append(user)
// update()
// })
}
// If there are no children, run completion here instead
if snapshot.childrenCount == 0 {
update()
}
})
}
**** IN VIEWDIDLOAD. ****
//THIS adds an observer and fills the userList array
FriendSystem.system.addUserObserver {
}

Update TableViewCell with Asynchronous data

I have a tableViewCell that contains 8 images total divided into two blocks (4 images in each block). These images are downloaded asynchronously and stored into an array and then used in the the tableViewCell's cellForRowAtIndexPath to populate the images. I reload the tableView when all the images for one block has been added to the array in the dictionary (groupTOImages). The way I am doing it, I am getting out of order inconsistent results with the loading of the data. Some images are loaded into places where they shouldn't be. Is there a way to download the images and get consistent results in the tableViewCell.
var groupNames = [NSManagedObject]()
var groupTOPeople = [NSManagedObject: [String]]()
var groupTOImages = [NSManagedObject: [UIImage]]()
func getGroups() {
...
for group in groupNames {
groupTOImages[group] = []
if let people = groupTOPeople[group] {
var mycount = 0
for peeps in people {
InstagramEngine.sharedEngine().getUserDetails(peeps, withSuccess: { user in
if let ppic = user.profilePictureURL {
let picUrl = ppic.absoluteString
print(picUrl)
ImageLoader.sharedLoader.imageForUrl(picUrl) { (image, url) -> () in
self.groupTOImages[group]?.append(image!)
mycount++
if mycount == people.count {
self.tableView.reloadData()
}
}
} else {
self.groupTOImages[group]?.append(UIImage())
mycount++
if mycount == people.count {
self.tableView.reloadData()
}
}
}, failure: nil )
}
}
}
var counter = 0
var groupCount = 0
var groupCounter = 0
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellInfo = GroupCellsArray[indexPath.section]
...
case .userGroups:
let cell = tableView.dequeueReusableCellWithIdentifier(cellInfo.description, forIndexPath: indexPath) as! GroupTableViewCell
if groupNames.count > 0 {
var gp = groupNames[groupCounter]
switch counter {
case 0:
cell.firstTitle.text = (gp.valueForKey("name") as! String)
if let ourImages = groupTOImages[gp] {
for image in ourImages {
print(image.description)
print("groupCount \(groupCounter)")
cell.firstUserButtons[groupCount].layer.borderWidth = 0
cell.firstUserButtons[groupCount].setImage(image, forState: .Normal)
groupCount++
if groupCount == ourImages.count {
groupCount = 0
counter++
groupCounter++
gp = groupNames[groupCounter]
}
}
}
case 1:
if let title = gp.valueForKey("name") as? String {
cell.secondTitle.text = title
if let ourImages = groupTOImages[gp] {
for image in ourImages {
cell.secondUserButtons[groupCount].layer.borderWidth = 0
cell.secondUserButtons[groupCount].setImage(image, forState: .Normal)
groupCount++
if groupCount == ourImages.count {
groupCount = 0
counter = 0
groupCounter++
gp = groupNames[groupCounter]
}
}
}
} else {
cell.secondTitle.text = "Title"
}
default:
break
}
Each row looks like the picture below:
Code using ImageLoader in cellForRowAtIndexPath:
var counter = 0
for group in groupNames {
print("in the second")
groupTOImages[group] = []
if let people = groupTOPeople[group] {
var mycount = 0
for peeps in people {
InstagramEngine.sharedEngine().getUserDetails(peeps, withSuccess: { user in
if let ppic = user.profilePictureURL {
let picUrl = ppic.absoluteString
self.groupTOImages[group]?.append(picUrl)
counter++
mycount++
if counter == self.groupNames.count && mycount == people.count
{
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
} else {
self.groupTOImages[group]?.append(nil)
counter++
mycount++
if counter == self.groupNames.count && mycount == people.count
{
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
}
}, failure: nil )
}
}
if groupNames.count > 0 {
var gp = groupNames[groupCounter]
print("counter!!!!")
print("groupCount \(counter)")
switch counter {
case 0:
if let ourImages = groupTOImages[gp] {
cell.firstTitle.text = (gp.valueForKey("name") as! String)
print(cell.firstTitle.text)
for image in ourImages {
if let url = image {
print("I get in here")
ImageLoader.sharedLoader.imageForUrl(url) { (image, url) -> () in
cell.firstUserButtons[self.groupCount].layer.borderWidth = 0
cell.firstUserButtons[self.groupCount].setImage(image, forState: .Normal)
self.groupCount++
if self.groupCount == ourImages.count {
self.groupCount = 0
self.counter++
self.groupCounter++
gp = self.groupNames[self.groupCounter]
}
}
} else {
self.groupCount++
if self.groupCount == ourImages.count {
self.groupCount = 0
self.counter++
self.groupCounter++
gp = self.groupNames[self.groupCounter]
}
}
}
}
case 1:
if let title = gp.valueForKey("name") as? String {
cell.secondTitle.text = title
if let ourImages = groupTOImages[gp] {
for image in ourImages {
if let url = image {
ImageLoader.sharedLoader.imageForUrl(url) { (image, url) -> () in
cell.secondUserButtons[self.groupCount].layer.borderWidth = 0
cell.secondUserButtons[self.groupCount].setImage(image, forState: .Normal)
self.groupCount++
if self.groupCount == ourImages.count {
self.groupCount = 0
self.counter++
self.groupCounter++
gp = self.groupNames[self.groupCounter]
}
}
} else {
self.groupCount++
if self.groupCount == ourImages.count {
self.groupCount = 0
self.counter = 0
self.groupCounter++
gp = self.groupNames[self.groupCounter]
}
}
}
}
} else {
cell.secondTitle.text = "Title"
}
You should replace the self.tableView.reloadData() with
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
Hope this helps!

app crashes when a button is clicked --- in SWIFT

Good Morning
I've a table view with multipel selection enabled of maximum 5 cells .. above it there is a list of 5 buttons and images .. when the user clicked on a cell a photo shall appear in the first empty imageViewabove the table, and when the user clicks on that photo it should disaapear and the cell color return to clear or white color in my case.
my problem is, when i click on a photo which cell is not shown because of scrolling, the app crashes. can you please help me .. how can i check if the indexpath is shown or not because the problem happened when it is not
here is my code :
#IBAction func btnClicked (sender : UIButton)
{
let tester = sender
if (tester == btn1 && img1.image != nil)
{
img1.image = nil
let cell1 = myTable.cellForRowAtIndexPath(img1IP)! as CustomCell
selectedIndexPaths.removeObject(img1IP)
configure(cell1, forRowAtIndexPath: img1IP)
counter--
}
else if (tester == btn2 && img2.image != nil)
{
img2.image = nil
let cell2 = myTable.cellForRowAtIndexPath(img2IP)! as CustomCell
selectedIndexPaths.removeObject(img2IP)
configure(cell2, forRowAtIndexPath: img2IP)
counter--
}
else if (tester == btn3 && img3.image != nil)
{
img3.image = nil
let cell3 = myTable.cellForRowAtIndexPath(img3IP)! as CustomCell
selectedIndexPaths.removeObject(img3IP)
configure(cell3, forRowAtIndexPath: img3IP)
counter--
}
else if (tester == btn4 && img4.image != nil)
{
img4.image = nil
let cell4 = myTable.cellForRowAtIndexPath(img4IP)! as CustomCell
selectedIndexPaths.removeObject(img4IP)
configure(cell4, forRowAtIndexPath: img4IP)
counter--
}
else if (tester == btn5 && img5.image != nil)
{
img5.image = nil
let cell5 = myTable.cellForRowAtIndexPath(img5IP)! as CustomCell
selectedIndexPaths.removeObject(img5IP)
configure(cell5, forRowAtIndexPath: img5IP)
counter--
}
else
{
println("its already empty")
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("intrest", forIndexPath: indexPath) as CustomCell
cell.selectionStyle = .None
cell.backgroundColor = UIColor.clearColor()
configure(cell, forRowAtIndexPath: indexPath)
return cell
}
func configure(cell: CustomCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.lblInCell.text = InterstArr[indexPath.row]
if selectedIndexPaths.containsObject(indexPath) {
// selected
cell.imgInCell.backgroundColor = UIColor.redColor()
}
else if (selectedIndexPaths.containsObject(indexPath) == false ) {
// not selected
cell.imgInCell.backgroundColor = UIColor.whiteColor()
cell.lblInCell.backgroundColor = UIColor.whiteColor()
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if selectedIndexPaths.containsObject(indexPath) {
// deselect
println("remove object")
selectedIndexPaths.removeObject(indexPath)
////////////
if (img1str == InterstArr[indexPath.row])
{
img1.image = nil
println("remove 1 object")
}
else if ( img2str == InterstArr[indexPath.row])
{
img2.image = nil
println("remove 2 object")
}
else if (img3str == InterstArr[indexPath.row])
{
img3.image = nil
println("remove 3 object")
}
else if (img4str == InterstArr[indexPath.row])
{
img4.image = nil
println("remove 4 object")
}
else if ( img5str == InterstArr[indexPath.row])
{
img5.image = nil
println("remove 5 object")
}
counter--
// println(counter)
}
else if !(selectedIndexPaths.containsObject(indexPath)) {
// select
if (counter <= 4){
if (img1.image == nil)
{
img1str = InterstArr[indexPath.row]
img1.image = UIImage(named: InterstArr[indexPath.row])
img1IP = indexPath
println("add 1 object")
}
else if (img2.image == nil)
{
img2str = InterstArr[indexPath.row]
img2IP = indexPath
img2.image = UIImage(named: InterstArr[indexPath.row])
println("add 2 object")
}
else if (img3.image == nil)
{
img3str = InterstArr[indexPath.row]
img3IP = indexPath
img3.image = UIImage(named: InterstArr[indexPath.row])
println("add 3 object")
}
else if (img4.image == nil)
{
img4str = InterstArr[indexPath.row]
img4IP = indexPath
img4.image = UIImage(named: InterstArr[indexPath.row])
println("add 4 object")
}
else if (img5.image == nil)
{
img5str = InterstArr[indexPath.row]
img5IP = indexPath
img5.image = UIImage(named: InterstArr[indexPath.row])
println("add 5 object")
}
selectedIndexPaths.addObject(indexPath)
counter++
}
else if (counter > 4)
{
println("you selected 5 already")
}
}
let cell = tableView.cellForRowAtIndexPath(indexPath)! as CustomCell
configure(cell, forRowAtIndexPath: indexPath)
}
Ok then .. the problem was how to check if the indexPath is shown, so here is my answer for those who have the same problem, as an example i posted only one part of the function and you can repeat if (tester == btn1 && img1.image != nil) for the other buttons .. the line to check if the indexPath is visible is this one if ((myTable.cellForRowAtIndexPath(img1IP)) != nil) :
#IBAction func btn1Clicked (sender : UIButton)
{
let tester = sender
if (tester == btn1 && img1.image != nil)
{
if ((myTable.cellForRowAtIndexPath(img1IP)) != nil)
{
println("1 exist")
let cell:CustomCell = myTable.cellForRowAtIndexPath(img1IP) as CustomCell!
cell.imgInCell.backgroundColor = UIColor.whiteColor()
img1.image = nil
selectedIndexPaths.removeObject(img1IP)
}
else
{
img1.image = nil
selectedIndexPaths.removeObject(img1IP)
}
}

Resources