I'm trying to combine a CollectionViewwith a TableView, so fare everything works except one problem, which I cant fix myself.
I have to load some data in the CollectionViews which are sorted with the header of the TableViewCell where the CollectionView is inside. For some reason, every time I start the app, the first three TableViewCells are identical. If I scroll a little bit vertically, they change to the right Data.
But it can also happen that while using it sometimes displays the same Data as in on TableViewCell another TableViewCell, here again the problem is solved if I scroll a little.
I think the problem are the reusableCells but I cant find the mistake myself. I tried to insert a colletionView.reloadData() and to set the cells to nil before reusing, sadly this didn`t work.
My TableViewController
import UIKit
import RealmSwift
import Alamofire
import SwiftyJSON
let myGroupLive = DispatchGroup()
let myGroupCommunity = DispatchGroup()
var channelTitle=""
class HomeVTwoTableViewController: UITableViewController {
var headers = ["LIVE","Channel1", "Channel2", "Channel3", "Channel4", "Channel5", "Channel6"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.navigationBar.isTranslucent = false
DataController().fetchDataLive(mode: "get")
DataController().fetchDataCommunity(mode: "get")
}
//MARK: Custom Tableview Headers
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return headers[section]
}
//MARK: DataSource Methods
override func numberOfSections(in tableView: UITableView) -> Int {
return headers.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
//Choosing the responsible PrototypCell for the Sections
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellBig", for: indexPath) as! HomeVTwoTableViewCell
print("TableViewreloadMain")
cell.collectionView.reloadData()
return cell
}
else if indexPath.section >= 1 {
// getting header Titel for reuse in cell
channelTitle = self.tableView(tableView, titleForHeaderInSection: indexPath.section)!
let cell = tableView.dequeueReusableCell(withIdentifier: "cellSmall", for: indexPath) as! HomeVTwoTableViewCellSmall
// anti Duplicate protection
cell.collectionView.reloadData()
return cell
}
else {
channelTitle = self.tableView(tableView, titleForHeaderInSection: indexPath.section)!
let cell = tableView.dequeueReusableCell(withIdentifier: "cellSmall", for: indexPath) as! HomeVTwoTableViewCellSmall
// anti Duplicate protection
cell.collectionView.reloadData()
return cell
}
}
}
}
My TableViewCell with `CollectionView
import UIKit
import RealmSwift
var communities: Results<Community>?
class HomeVTwoTableViewCellSmall: UITableViewCell{
//serves as a translator from ChannelName to the ChannelId
var channelOverview: [String:String] = ["Channel1": "399", "Channel2": "401", "Channel3": "360", "Channel4": "322", "Channel5": "385", "Channel6": "4"]
//Initiaize the CellChannel Container
var cellChannel: Results<Community>!
//Initialize the translated ChannelId
var channelId: String = ""
#IBOutlet weak var collectionView: UICollectionView!
}
extension HomeVTwoTableViewCellSmall: UICollectionViewDataSource,UICollectionViewDelegate {
//MARK: Datasource Methods
func numberOfSections(in collectionView: UICollectionView) -> Int
{
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return (cellChannel.count)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCellSmall", for: indexPath) as? HomeVTwoCollectionViewCellSmall else
{
fatalError("Cell has wrong type")
}
//removes the old image and Titel
cell.imageView.image = nil
cell.titleLbl.text = nil
//inserting the channel specific data
let url : String = (cellChannel[indexPath.row].pictureId)
let name :String = (cellChannel[indexPath.row].communityName)
cell.titleLbl.text = name
cell.imageView.downloadedFrom(link :"link")
return cell
}
//MARK: Delegate Methods
override func layoutSubviews() {
myGroupCommunity.notify(queue: DispatchQueue.main, execute: {
let realm = try! Realm()
//Getting the ChannelId from Dictionary
self.channelId = self.channelOverview[channelTitle]!
//load data from Realm into variables
self.cellChannel = realm.objects(Community.self).filter("channelId = \(String(describing: self.channelId)) ")
self.collectionView.dataSource = self
self.collectionView.delegate = self
print("collectionView layout Subviews")
self.collectionView.reloadData()
})
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedCommunity = (cellChannel[indexPath.row].communityId)
let home = HomeViewController()
home.showCommunityDetail()
}
}
Thanks in advance.
tl;dr make channelTitle a variable on your cell and not a global variable. Also, clear it, and your other cell variables, on prepareForReuse
I may be mistaken here, but are you setting the channelTitle on the cells once you create them? As I see it, in your viewController you create cells based on your headers, and for each cell you set TableViewController's channelTitle to be the title at the given section.
If this is the case, then the TableViewCell actually isn't receiving any information about what it should be loading before you call reloadData().
In general, I would also recommend implementing prepareForReuse in your HomeVTwoTableViewCellSmall, since it will give you a chance to clean up any stale data. Likely you would want to do something like set cellChannel and channelId to empty strings or nil in that method, so when the cell is reused that old data is sticking around.
ALSO, I just reread the cell code you have, and it looks like you're doing some critical initial cell setup in layoutSubviews. That method is going to be potentially called a lot, but you really only need it to be called once (for the majority of what it does). Try this out:
override the init with reuse identifier on the cell
in that init, add self.collectionView.dataSource = self and self.collectionView.delegate = self
add a didSet on channelTitle
set channelTitle in the viewController
So the code would look like:
var channelTitle: String = "" {
didSet {
self.channelId = self.channelOverview[channelTitle]!
self.cellChannel = realm.objects(Community.self).filter("channelId = \(String(describing: self.channelId)) ")
self.collectionView.reloadData()
}
}
This way you're only reloading your data when the cell is updated with a new channel, rather than every layout of the cell's views.
Sorry... one more addition. I wasn't aware of how your channelTitle was actually being passed. As I see it, you're using channelTitle as a global variable rather than a local one. Don't do that! remove channelTitle from where it is currently before implementing the code above. You'll see some errors, because you're setting it in the ViewController and accessing it in the cell. What you want is to set the channelTitle on the cell from the ViewController (as I outlined above). That also explains why you were seeing the same data across all three cells. Basically you had set only ONE channelTitle and all three cells were looking to that global value to fetch their data.
Hope that helps a little!
(also, you should be able to remove your else if block in the cellForRowAtIndexPath method, since the else block that follows it covers the same code. You can also delete your viewDidLoad, since it isn't doing anything, and you should, as a rule, see if you can get rid of any !'s because they're unsafe. Use ? or guard or if let instead)
The cell is initially created from a xib file. Ive registered a reuse identifier in viewDidLoad().
Whenever I scroll down, one specific label is redrawn partially. Cant seem to figure out whats going on with the cell, but I know that the cell is not nil. Looking for insight on why this label isn't being drawn correctly.
before dragging
after dragging
More Info:
I can't tell, but it seems as if new cells are being drawn directly on top of the old cells. I figured this out due to the custom line divider: (let lineView = self.createLineDivider(cell: cell)) I added to context view of the cell. To stop the line from drawing over itself, I change the tag of every new cell.
override func viewDidLoad()
{
super.viewDidLoad()
let nib = UINib(nibName: "customContactDetailTableViewCell", bundle: nil)
self.contactDetailsTableView.register(nib, forCellReuseIdentifier: "customDetailCell")
}
func configureCell(cell: customContactDetailTableViewCell, indexPath: IndexPath) -> customContactDetailTableViewCell
{
let sectionName = self.props[indexPath.section].keys.first!
let contactPropLabel = self.props[indexPath.section][sectionName]![indexPath.row].keys.first!
let contactProp = self.props[indexPath.section][sectionName]![indexPath.row][contactPropLabel]
cell.contactDetailInfo?.layer.borderWidth = 1
cell.contactDetailInfo?.layer.borderColor = UIColor.white.cgColor
cell.contactDetailInfoTitle?.layer.borderWidth = 1
cell.contactDetailInfoTitle?.layer.borderColor = UIColor.white.cgColor
cell.contactDetailInfo?.numberOfLines = 0
cell.contactDetailInfoTitle?.text = contactPropLabel
cell.contactDetailInfo?.text = contactProp
cell.contactDetailInfo?.lineBreakMode = .byWordWrapping
self.rowHeight = cell.bounds.height
return cell
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{ var cell = tableView.dequeueReusableCell(withIdentifier: "customDetailCell") as? customContactDetailTableViewCell
if cell?.tag != 212
{
cell?.tag = 212
cell?.backgroundColor = UIColor.clear
let lineView = self.createLineDivider(cell: cell)
cell?.contentView.addSubview(lineView)
}
return self.configureCell(cell: cell!, indexPath: indexPath)
}
Update
Figured it out. Looks like the sporadic behavior came from the table view not updating the row height quick enough. Used this instead:
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
I am trying to create a contacts page where you can see all your contacts with a friend request cell showing up when you receive a friend request, but not there when you do not have any. At the moment, both custom cells work fine. The issue I have is that the contactRequestTableViewCell overlaps the first cell of the contactListTableViewCell.
I have researched other questions about two custom tableviewcells and none are quite having the same issues that I am facing.
Here is my executing code at the moment, I am returning 2 sections in the table view.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! ContactListTableViewCell
let requestCell = tableView.dequeueReusableCellWithIdentifier("requestCell", forIndexPath: indexPath) as! ContactRequestsTableViewCell
let user = OneRoster.userFromRosterAtIndexPath(indexPath: indexPath)
if (amountOfBuddyRequests > 0) {
if (indexPath.section == 0) {
requestCell.hidden = false
cell.hidden = false
requestCell.friendRequestLabel.text = "test"
} else if (indexPath.section >= 1) {
cell.contactNameLabel!.text = user.displayName;
cell.contactHandleLabel!.text = "# " + beautifyJID(user.jidStr)
cell.contactHandleLabel!.textColor = UIColor.grayColor()
OneChat.sharedInstance.configurePhotoForImageView(cell.imageView!, user: user)
}
return cell;
}
else { // if buddy requests == 0
requestCell.hidden = true
cell.contactNameLabel!.text = user.displayName;
cell.contactHandleLabel!.text = "# " + beautifyJID(user.jidStr)
cell.contactHandleLabel!.textColor = UIColor.grayColor()
print ("This is how many unreadMessages it has \(user.unreadMessages)")
// If there is unread messages for a person highlight it blue
// However this feature isn't working right now due to unreadMessages bug
if user.unreadMessages.intValue > 0 {
cell.backgroundColor = .blueColor()
} else {
cell.backgroundColor = .whiteColor()
}
OneChat.sharedInstance.configurePhotoForCell(cell, user: user)
return cell;
}
}
This is the current output that I have right now, my cells that have "test" are covering up other contactListTableViewCells.
The function tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell should always return one and the only one TableViewCell you want at indexPath, so you don't want to always return cell of type ContactListTableViewCell.
According to documentation, the cellForRowAtIndexPath tableView method asks for the cell at the indexPath, which means literally there can only be one cell at certain row of a certain section, so returning two cells is not an option.
I suggest you use two arrays to store the requests and contacts information. For example, you have arrays requests and contacts. Then you can tell the tableView how many rows you want:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return requests.count + contacts.count
}
and then in cellForRowAtIndexpath you do something like:
override func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row < requests.count {
// return a request cell
}
else {
// return a contact cell
}
}
I'm only using one tableView section here. If you still want two sections you can simply return 2 in numberOfSections function and add if statements in cellForRowAtIndexPath for indexPath.section.
Hope this helps.
It turns out that the issue was dealing with the data sources. My data sources were not pointing to the correct tableviewcell. This resulted in them pointing to an incorrect cell. This issue was fixed by remaking the data sources system that was in place. This issue will not affect most as the data sources will point to the correct tableviewcell by default.
Contrary to what another poster said, you can in fact display two or more custom cells in a single table. This is how I fixed the tableView display issues:
var friendRequests = ["FriendRequest1", "FriendRequest2"]
var contacts = ["User1","User2","User3","User4"]
var amountOfBuddyRequests = 1
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if (amountOfBuddyRequests > 0) {
return 2
}
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (amountOfBuddyRequests > 0) {
if (section == 0) {
return friendRequests.count
}
}
return contacts.count
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (amountOfBuddyRequests > 0) {
if (indexPath.section == 0) {
let requestCell = tableView.dequeueReusableCellWithIdentifier("requestCell") as! ContactRequestsTableViewCell
requestCell.friendRequestLabel.text = friendRequests[indexPath.row]
requestCell.onButtonTapped = {
self.friendRequests.removeAtIndex(indexPath.row)
self.tableView.reloadData()
}
requestCell.addButtonTapped = {
self.addUser(self.friendRequests[indexPath.row])
self.friendRequests.removeAtIndex(indexPath.row)
self.tableView.reloadData()
}
return requestCell
}
}
let friendCell = tableView.dequeueReusableCellWithIdentifier("FriendCell") as! ContactListTableViewCell
friendCell.contactNameLabel.text = contacts[indexPath.row]
return friendCell
}
I'm making a simple table view app to display and play all the iOS System sounds.
I have all of the sounds and ID's in a a dictionary(I now realize this was a bad way to do this) in the form of [ID(Int):Name(String)], the problem is that when I load my view it loads well, but if I scroll down the cells originally on top change. Same when scrolling from the bottom to the top.
For example, the view loads in and I can click and hear the various sounds from any of the cells I click on. Lets say the first cell is "SMS-Sound1" and the seconds is "SMS-Sound2". Now when I scroll down to where those cells are out of view and then scroll back to the the top they are named something different(Still from my data dictionary).
How would I fix this problem so that it loads the tableview and then the tableview data doesn't change?
Edit: I thought the problem could be in the fact that the for in loop was executed around 300,000 times but thats not the case, made an array of the IDS so it was only executed around 1000 times total and the problem persists
My Code:
Cell set up
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("soundCell", forIndexPath: indexPath)
let button = cell.viewWithTag(3) as! UILabel //UILabel in "SoundCell"
for i: Int in 999..<4100 {
//Lowest id sound is 1000, highest is 4095
if (sounds[i] != nil) && loadedSoundStrings.contains(sounds[i]!) == false {
button.text = sounds[i]
loadedSoundStrings.append(sounds[i]!)
cell.tag = i
break
}
}
return cell
}
Rows/sections
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sounds.count
}
Variables:
let sounds =
[ 1000:"new-mail.caf",
1001:"mail-sent.caf",
1002:"Voicemail.caf",
1003:"ReceivedMessage.caf",
1004:"SentMessag.caf",
1005:"alarm.caf",
1006:"low-power.caf",
1007:"sms-received1.caf",
1008:"sms-received2.caf",
1009:"sms-received3.caf",
1010:"sms-received4.caf",
1011:"-(SMSReceived_Vibrate)",
1012:"sms-received1.caf",
1013:"sms-received5.caf",
1014:"sms-received6.caf",
1015:"Voicemail.caf",
1016:"tweet_sent.caf",
1020:"Anticipate.caf",
1021:"Bloom.caf",
1022:"Calypso.caf",
1023:"Choo_Choo.caf",
1024:"Descent.caf",
1025:"Fanfare.caf",
1026:"Ladder.caf",
1027:"Minuet.caf",
1028:"News_Flash.caf",
1029:"Noir.caf",
1030:"Sherwood_Forest.caf",
1031:"Spell.caf",
1032:"Suspense.caf",
1033:"Telegraph.caf",
1034:"Tiptoes.caf",
1035:"Typewriters.caf",
1036:"Update.caf",
1050:"ussd.caf",
1051:"SIMToolkitCallDropped.caf",
1052:"SIMToolkitGeneralBeep.caf",
1053:"SIMToolkitNegativeACK.caf",
1054:"SIMToolkitPositiveACK.caf",
1055:"SIMToolkitSMS.caf",
1057:"Tink.caf",
1070:"ct-busy.caf",
1071:"ct-congestion.caf",
1072:"ct-path-ack.caf",
1073:"ct-error.caf",
1074:"ct-call-waiting.caf",
1075:"ct-keytone2.caf",
1100:"lock.caf",
1101:"unlock.caf",
1102:"-(FailedUnlock)",
1103:"Tink.caf",
1104:"Tock.caf",
1105:"Tock.caf",
1106:"beep-beep.caf",
1107:"RingerChanged.caf",
1108:"photoShutter.caf",
1109:"shake.caf",
1110:"jbl_begin.caf",
1111:"jbl_confirm.caf",
1112:"jbl_cancel.caf",
1113:"begin_record.caf",
1114:"end_record.caf",
1115:"jbl_ambiguous.caf",
1116:"jbl_no_match.caf",
1117:"begin_video_record.caf",
1118:"end_video_record.caf",
1150:"vc~invitation-accepted.caf",
1151:"vc~ringing.caf",
1152:"vc~ended.caf",
1153:"ct-call-waiting.caf",
1154:"vc~ringing.caf",
1200:"dtmf-0.caf",
1201:"dtmf-1.caf",
1202:"dtmf-2.caf",
1203:"dtmf-3.caf",
1204:"dtmf-4.caf",
1205:"dtmf-5.caf",
1206:"dtmf-6.caf",
1207:"dtmf-7.caf",
1208:"dtmf-8.caf",
1209:"dtmf-9.caf",
1210:"dtmf-star.caf",
1211:"dtmf-pound.caf",
1254:"long_low_short_high.caf",
1255:"short_double_high.caf",
1256:"short_low_high.caf",
1257:"short_double_low.caf",
1258:"short_double_low.caf",
1259:"middle_9_short_double_low.caf",
1300:"Voicemail.caf",
1301:"ReceivedMessage.caf",
1302:"new-mail.caf",
1303:"mail-sent.caf",
1304:"alarm.caf",
1305:"lock.caf",
1306:"Tock.caf",
1307:"sms-received1.caf",
1308:"sms-received2.caf",
1309:"sms-received3.caf",
1310:"sms-received4.caf",
1311:"-(SMSReceived_Vibrate)",
1312:"sms-received1.caf",
1313:"sms-received5.caf",
1314:"sms-received6.caf",
1315:"Voicemail.caf",
1320:"Anticipate.caf",
1321:"Bloom.caf",
1322:"Calypso.caf",
1323:"Choo_Choo.caf",
1324:"Descent.caf",
1325:"Fanfare.caf",
1326:"Ladder.caf",
1327:"Minuet.caf",
1328:"News_Flash.caf",
1329:"Noir.caf",
1330:"Sherwood_Forest.caf",
1331:"Spell.caf",
1332:"Suspense.caf",
1333:"Telegraph.caf",
1334:"Tiptoes.caf",
1335:"Typewriters.caf",
1336:"Update.caf",
1350:"-(RingerVibeChanged)",
1351:"-(SilentVibeChanged)",
4095:"-(Vibrate)"]
var loadedSoundStrings = [String]()
You are instantiating all of the sounds for every single row when you actually want to only instantiate the sound for the rows that are loaded. To fix your order issue change your
cellForRowAtIdexPath
to this:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("soundCell", forIndexPath: indexPath)
let button = cell.viewWithTag(3) as! UILabel //UILabel in "SoundCell"
button.text = sounds[i]
cell.tag = indexPath.row
return cell
}
This gives you 1 sound per cell since you have NumberOfRowsInSection set to sounds.count Cell for row will be called for every sound you have.
If I understand your code correctly, you're going about it the wrong way. You have a dictionary of sounds that you load once. The cellForRowAtIndexPath function should be returning one tableViewCell with details for the one sound.
UITableView automatically discards cells that are off screen to conserve memory, and will reuse them for newly visible cells. That's why you call dequeueReusableCellWithIdentifier. Therefore you should just be doing:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("soundCell", forIndexPath: indexPath)
let button = cell.viewWithTag(3) as! UILabel //UILabel in "SoundCell"
//Lowest id sound is 1000, highest is 4095
let i = indexPath.row + 1000
button.text = sounds[i]
cell.tag = i
return cell
}
Since you are hardcoding the sound number range I have done the same.
A table view works best with an array, as an array has a defined order and you can quickly access a given element; a for loop in cellForRowAtIndexPath is seldom a good thing.
You have a couple of issues, however, as your sounds identifiers don't start from 0, you can't use the identifier as a direct index into the array, but also the identifiers aren't sequential, so you can't even use a simple offset (adding a constant value to the row number).
I think that the best solution is not to rely directly on intrinsic types as you are for your dictionary, but rather, create a struct for each sound and store an array of them. Something like this:
class MyViewController: UIViewController, UITableViewDelegate, UITableViewDatasource
struct Sound {
var id:Int
var fileName:String
}
var sounds=[Sound]()
func loadSounds() {
let soundsDict =
[1000:"new-mail.caf",
1001:"mail-sent.caf",
1002:"Voicemail.caf",
1003:"ReceivedMessage.caf",
1004:"SentMessag.caf",
1005:"alarm.caf",
1006:"low-power.caf",
1007:"sms-received1.caf",
1008:"sms-received2.caf",
...
]
for (id,fileName) in soundsDict {
self.sounds.append(Sound(id: id, fileName: fileName))
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("soundCell", forIndexPath: indexPath)
let button = cell.viewWithTag(3) as! UILabel //UILabel in "SoundCell"
button.text=self.sounds[indexPath.row].fileName
return cell
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.sounds.count
}
}
I have been struggling with this issue. I can scroll freely between the tag cells because it actually remembers them. But if I get the description cell out of my view it immediately removes it from memory and doesn't get it back. Instead I just get "fatal error: unexpectedly found nil while unwrapping an Optional value" when I scroll back to the description. So I have the following pieces of code:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44.0
tableView.reloadData()
}
I don't know if the viewWillAppear is of any importance in this case but if it is then tell me. Anyway, this is for filling in the cells in my table view:
func GetDescription(cell:descCell, indexPath: NSIndexPath) {
cell.descText.text = descriptTextTwo.htmlToString
}
func GetTagCell(cell:basicTag, indexPath: NSIndexPath) {
let item = tagResults[indexPath.row]!
cell.titleLabel.text = item["tagname"]?.htmlToString
}
func GetValueCell(cell: basicTag, indexPath: NSIndexPath) {
let item = tagResults[indexPath.row]!
cell.valueLabel.text = item["value"]?.htmlToString
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if filledDescription == false {
return getDescriptionAtIndexPath(indexPath)
} else {
return getTagAtIndexPath(indexPath)
}
}
func getDescriptionAtIndexPath(indexPath:NSIndexPath) -> descCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier(descriptionCell) as descCell
GetDescription(cell, indexPath: indexPath)
filledDescription = true
return cell
}
func getTagAtIndexPath(indexPath: NSIndexPath) -> basicTag {
let cell = self.tableView.dequeueReusableCellWithIdentifier(tagCell) as basicTag
GetTagCell(cell, indexPath: indexPath)
GetValueCell(cell, indexPath: indexPath)
return cell
}
So how can I make Swift remember what is in the first cell? Because I am guessing that that is what happens, that it removes what was in the first cell as soon as you get it out of the view. I am guessing I have to do something with "indexPath" but I am not exactly sure how to implement it in this case and if I am far off, please tell me what I am doing wrong. Thanks!
Change the following :
if filledDescription == false {
return getDescriptionAtIndexPath(indexPath)
} else {
return getTagAtIndexPath(indexPath)
}
With:
if indexPath.row == 0 {
return getDescriptionAtIndexPath(indexPath)
} else {
return getTagAtIndexPath(indexPath)
}
This will make sure that the first cell in the table will always treated as a "Description" cell. Since the filledDescription never becomes false after your set it to true, when you get back to the first cell it is treated as a "Tag" cell (due to the if line) where in fact the reusable cell contains "Description" cell data