How to get cells with different cell classes - ios

I need to get the text from the textfield i.e from KgCustomCell and KgRepsCustomCell. I need to fetch the data from the field, when i run the buttonClicked method.
I have tried to add to instance variables, which contains kg and reps, but the first time i click the button, it's empty. The second time it's okay. But how can i load the data in the most correct way?
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let index = indexPath.row
if indexPath.row == 0 && indexPath.section == 0 {
let exerciseName = tableView.dequeueReusableCellWithIdentifier("Exercise Name", forIndexPath: indexPath) as! LoggedExerciseNameCell
exerciseName.lblExerciseName.text = self.exercise?.name
return exerciseName
}
if index == 0 && indexPath.section == 1 {
let txtFieldKg = tableView.dequeueReusableCellWithIdentifier("Text KG", forIndexPath: indexPath) as! KgCustomCell
return txtFieldKg
}
if index == 1 && indexPath.section == 1 {
let txtFieldReps = tableView.dequeueReusableCellWithIdentifier("Text Reps", forIndexPath: indexPath) as! KgRepsCustomCell
//kg = txtFieldReps.textReps.text
return txtFieldReps
}
if index == 2 && indexPath.section == 1 {
let btnLog = tableView.dequeueReusableCellWithIdentifier("Button Log", forIndexPath: indexPath) as! ButtonLogWorkoutCustomCell
btnLog.btnLogExercise.addTarget(self, action: #selector(AddLogViewController.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
// kg = txtFieldReps.textReps.text
return btnLog
}
if indexPath.section == 2 {
let loggedExerciseInformation = tableView.dequeueReusableCellWithIdentifier("Logged Exercise", forIndexPath: indexPath) as! LoggedExerciseCustomCell
return loggedExerciseInformation
}
let noCell = tableView.dequeueReusableCellWithIdentifier("Button Log", forIndexPath: indexPath)
return noCell
}
func buttonClicked(sender:UIButton) {
let button = sender as UIButton
if let superview = button.superview {
if (superview.superview as? ButtonLogWorkoutCustomCell) != nil {
try! LogManagerDAO.sharedInstance.realm.write({
exercise?.loggedKg = 4//Int(txtKG.text!)!
exercise?.loggedReps = 4//Int(txtReps.text!)!
log!.addExerciseToLog(exercise!)
loadLoggedExercise()
tableView.reloadData()
})
}
}
}

If you just want the text of that textField than you can use delegate method of UITextField like this, first declare two instance var for that 2 textField's value
var strKG: String = ""
var strReps: String = ""
Now set delegate with textField in cellForRowAtIndexPath
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let index = indexPath.row
if indexPath.row == 0 && indexPath.section == 0 {
let exerciseName = tableView.dequeueReusableCellWithIdentifier("Exercise Name", forIndexPath: indexPath) as! LoggedExerciseNameCell
exerciseName.lblExerciseName.text = self.exercise?.name
return exerciseName
}
if index == 0 && indexPath.section == 1 {
let txtFieldKg = tableView.dequeueReusableCellWithIdentifier("Text KG", forIndexPath: indexPath) as! KgCustomCell
txtFieldReps.textField.tag = index
txtFieldKg.textField.delegate = self
return txtFieldKg
}
if index == 1 && indexPath.section == 1 {
let txtFieldReps = tableView.dequeueReusableCellWithIdentifier("Text Reps", forIndexPath: indexPath) as! KgRepsCustomCell
txtFieldReps.textField.tag = index
txtFieldReps.textField.delegate = self
return txtFieldReps
}
if index == 2 && indexPath.section == 1 {
let btnLog = tableView.dequeueReusableCellWithIdentifier("Button Log", forIndexPath: indexPath) as! ButtonLogWorkoutCustomCell
btnLog.btnLogExercise.addTarget(self, action: #selector(AddLogViewController.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
// kg = txtFieldReps.textReps.text
return btnLog
}
if indexPath.section == 2 {
let loggedExerciseInformation = tableView.dequeueReusableCellWithIdentifier("Logged Exercise", forIndexPath: indexPath) as! LoggedExerciseCustomCell
return loggedExerciseInformation
}
let noCell = tableView.dequeueReusableCellWithIdentifier("Button Log", forIndexPath: indexPath)
return noCell
}
Now add delegate method of UITextField
func textFieldDidEndEditing(textField: UITextField) {
if(textField.tag == 0) {
self.strKG = textField.text
}
else {
self.strReps = textField.text
}
}
Now just use this two string object in your button action method.

Related

Swift 5 UITableViewCell : Expand one section and collapse the expanded section

I have implemented the following code to add expand/collapse feature to UITableView sections. When user click each section1, it expands and when we click the same section1 it collapses. But, I want the section1 to collapse, if I am expanding section2. How can I implement this feature to my code added below.
struct FaqData{
var faqHead = String()
var faqImage = String()
var questionArray : [(question : String, answer : String, answerurl : String)] = [(String,String,String)]()
var openSection = Bool()
}
var supportArray = [FaqData]()
func numberOfSections(in tableView: UITableView) -> Int {
return supportArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0{
return 1
}
else{
if supportArray[section].openSection == true{
return supportArray[section].questionArray.count + 1
}else{
return 1
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
if indexPath.section == 0{
let cell = tableView.dequeueReusableCell(withIdentifier: "SupportCenterID", for: indexPath) as! SupportCenterTableViewCell
cell.selectionStyle = UITableViewCell.SelectionStyle.none
cell.faqCollection.reloadData()
return cell
}
else{
if indexPath.row == 0{
let cell = tableView.dequeueReusableCell(withIdentifier: "SupportFaqID") as! SupportCenterFaqTableViewCell
cell.selectionStyle = UITableViewCell.SelectionStyle.none
let faqHead = supportArray[indexPath.section].faqHead
cell.imageText.text = faqHead.capitalized
cell.imageButton.setImage(UIImage(named: supportArray[indexPath.section].faqImage), for: .normal)
return cell
}
else{
let cell = tableView.dequeueReusableCell(withIdentifier: "QuestionID") as! SupportQuestionTableViewCell
cell.selectionStyle = UITableViewCell.SelectionStyle.none
cell.isSelected = true
cell.questionLabel.text = "Q.\(indexPath.row) " + supportArray[indexPath.section].questionArray[indexPath.row - 1].question
cell.answerLabel.text = supportArray[indexPath.section].questionArray[indexPath.row - 1].answer
print(supportArray[indexPath.section].questionArray[indexPath.row - 1].answerurl)
if supportArray[indexPath.section].questionArray[indexPath.row - 1].answerurl == ""{
cell.urlButton.isHidden = true
}
else{
cell.urlButton.isHidden = false
}
cell.urlButton.isHidden = true
cell.urlButton.tag = indexPath.row
UserDefaults.standard.set(indexPath.section, forKey: "SectionValue")
cell.urlButton.addTarget(self, action: #selector(urlButtonClicked(_:)), for: .touchUpInside)
cell.layoutMargins = UIEdgeInsets.zero
return cell
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if supportArray[indexPath.section].openSection == true{
if indexPath.section != 0{
if indexPath.row == 0{
let cell = tableView.cellForRow(at: indexPath) as! SupportCenterFaqTableViewCell
cell.faqView.backgroundColor = .white
cell.imageButton.tintColor = UIColor(hexString: "#D71B61")
cell.imageText.textColor = UIColor(hexString: "#D71B61")
}
}
supportArray[indexPath.section].openSection = false
let sections = IndexSet.init(integer: indexPath.section)
tableView.reloadSections(sections, with: .fade)
}
else{
supportArray[indexPath.section].openSection = true
let sections = IndexSet.init(integer: indexPath.section)
tableView.reloadSections(sections, with: .fade)
if indexPath.section != 0{
if indexPath.row == 0{
let cell = tableView.cellForRow(at: indexPath) as! SupportCenterFaqTableViewCell
cell.faqView.backgroundColor = UIColor(hexString: "#D71B61")
cell.imageButton.tintColor = .white
cell.imageText.textColor = .white
}
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
Can anyone provide a solution for this?
do this in didselecterow method. This is the else case of your condition
// You will need to reload multiple sections. So make an array.
var reloadSections = [Int]()
// find already opened array
if let alreadyOpenSection = supportArray.firstIndex(where: { (faq) -> Bool in
return faq.openSection
}) {
// if found, toggle the openSections bit
supportArray[alreadyOpenSection].openSection = false
// add it to reload sections array
reloadSections.append(alreadyOpenSection)
}
supportArray[indexPath.section].openSection = true
reloadSections.append(indexPath.section)
// create index set with reload sections array
let sections = IndexSet.init(reloadSections)
tableView.reloadSections(sections, with: .fade)
// below code is same
if indexPath.section != 0{
if indexPath.row == 0{
let cell = tableView.cellForRow(at: indexPath) as! SupportCenterFaqTableViewCell
cell.faqView.backgroundColor = UIColor(hexString: "#D71B61")
cell.imageButton.tintColor = .white
cell.imageText.textColor = .white
}
}

Can not update the value in class

This is my class Designed.
open class SBCity: NSObject {
var CM_CityID:String = ""
var CM_CityName:String = ""
var CM_OrderBy:Int = 0
required public init(CM_CityID:String,CM_CityName:String,CM_OrderBy:Int) {
self.CM_CityID = CM_CityID
self.CM_CityName = CM_CityName
self.CM_OrderBy = CM_OrderBy
}
}
ViewController
In the ViewController I have the tableView contain the following three details in each cell. I just append the value in the class on my UITableView didSelect method.
var source:SBCity?
var destination:SBCity?
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if filterdata.count != 0 {
return filterdata.count
} else {
if tableView == FirstTable {
return ArrcityList.count
} else {
return ArrcityList.count
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == FirstTable{
let cell = tableView.dequeueReusableCell(withIdentifier: "RecentCityCell") as! RecentCityCell
cell.cities = ArrcityList[indexPath.row]
return cell
}
//if tableView is not table1 then
if filterdata.count != 0 {
let cell2 = tableView.dequeueReusableCell(withIdentifier: "SourceCityCell")
as! SourceCityCell
cell2.cities = filterdata[indexPath.row]
return cell2
} else {
let cell2 = tableView.dequeueReusableCell(withIdentifier: "SourceCityCell")
as! SourceCityCell
cell2.cities = ArrcityList[indexPath.row]
return cell2
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if isSelectingSource {
if tableView == FirstTable{
let indexPath = tableView.indexPathForSelectedRow
let crrtCell = tableView.cellForRow(at: indexPath!) as! RecentCityCell
self.source = SBCity(CM_CityID: crrtCell.lblID.text!, CM_CityName: crrtCell.lblCity1.text!, CM_OrderBy: 0)
source = SBCity(CM_CityID: crrtCell.lblID.text!, CM_CityName: crrtCell.lblCity1.text!, CM_OrderBy: 0)
SourceCityName = crrtCell.lblCity1.text!
self.moveOnNextVc()
} else {
let indexPath = tableView.indexPathForSelectedRow
let crrtCell = tableView.cellForRow(at: indexPath!) as! SourceCityCell
self.source = SBCity(CM_CityID: crrtCell.lblID2.text!, CM_CityName: crrtCell.lblCity2.text!, CM_OrderBy: 0)
source = SBCity(CM_CityID: crrtCell.lblID2.text!, CM_CityName: crrtCell.lblCity2.text!, CM_OrderBy: 0)
SourceCityName = crrtCell.lblCity2.text!
self.moveOnNextVc()
}
} else if isSelectingDestination {
if tableView == FirstTable{
let indexPath = tableView.indexPathForSelectedRow
let crrtCell = tableView.cellForRow(at: indexPath!) as! RecentCityCell
self.destination = SBCity(CM_CityID: crrtCell.lblID.text!, CM_CityName: crrtCell.lblCity1.text!, CM_OrderBy: 0)
destination = SBCity(CM_CityID: crrtCell.lblID.text!, CM_CityName: crrtCell.lblCity1.text!, CM_OrderBy: 0)
DestinationCityName = crrtCell.lblCity1.text!
self.moveOnNextVc()
} else {
let indexPath = tableView.indexPathForSelectedRow
let crrtCell = tableView.cellForRow(at: indexPath!) as! SourceCityCell
self.destination = SBCity(CM_CityID: crrtCell.lblID2.text!, CM_CityName: crrtCell.lblCity2.text!, CM_OrderBy: 0)
destination = SBCity(CM_CityID: crrtCell.lblID2.text!, CM_CityName: crrtCell.lblCity2.text!, CM_OrderBy: 0)
DestinationCityName = crrtCell.lblCity2.text!
self.moveOnNextVc()
}
}
}
But it does not append the value in the class. it's showing nil every time. What's the wrong with the code?

Adding an ad after every 5 cells in tableview is replacing content

I've search on stackoverflow for a hint on how to do that and I found this question here but that did not solved my problem, I want the same thing( add an advertise after every 5 rows), and I tried the solution mentioned there, but what I'm getting is the first row is being replaced by the ad, as the 5th, and so on, my normal content is being replaced by the ad.
So I want to achieve this:
row 0 = normal content
row 1 = normal content
row 2 = normal content
row 3 = normal content
row 4 = normal content
row 5 = ad
row 6 = normal content
...
here is what I tried:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath.row % 5 == 0 && indexPath.row != 0) {
if let cellBanner = tableView.dequeueReusableCell(withIdentifier: "cellBanner", for: indexPath) as? BannerCell {
return cellBanner
} else {
return UITableViewCell()
}
} else {
if let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? AnuncioCell {
if AnunciosService.instance.anuncios.count >= indexPath.row {
let anuncio = AnunciosService.instance.anuncios[indexPath.row]
let rowsToLoadFromBottom = 5;
let rowsLoaded = AnunciosService.instance.anuncios.count
if (!self.fetchingMore && (indexPath.row - (indexPath.row / 5) >= (rowsLoaded - rowsToLoadFromBottom))) {
let totalRows = AnunciosService.instance.anunciosCount
let remainingAnunciosToLoad = totalRows - rowsLoaded;
if (remainingAnunciosToLoad > 0) {
self.loadMoreAnuncios()
}
}
cell.configureCell(anuncio: anuncio)
let checkValue = Double(anuncio.user.nota)!
if checkValue < 1.0 {
cell.notaView.isHidden = true
}else{
cell.notaView.isHidden = false
}
if anuncio.destaque {
cell.destaque.isHidden = false
} else {
cell.destaque.isHidden = true
}
if anuncio.status == 0 {
if cell.imgAnuncio.image != nil{
Noir(originalImage: cell.imgAnuncio)
}
cell.sold_out.isHidden = false
cell.selectionStyle = .none
cell.isUserInteractionEnabled = false;
} else {
cell.sold_out.isHidden = true
cell.isUserInteractionEnabled = true;
cell.selectionStyle = .default
}
}
return cell
} else {
return UITableViewCell()
}
}
}
numberOfRowsInSection:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if AnunciosService.instance.anuncios.count == 0 {
return 0
}
return AnunciosService.instance.anuncios.count + BannersService.instance.banners.count
}
I was doing it wrong, for those who want to know how I solved it:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let index = indexPath.row + 1
if (index % 6 == 0 && indexPath.row != 0 && index/6 <= BannersService.instance.banners.count) {
let cellBanner = tableView.dequeueReusableCell(withIdentifier: "cellBanner", for: indexPath) as! BannerCell
return cellBanner
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AnuncioCell
let index = indexPath.row - (indexPath.row / 6)
if AnunciosService.instance.anuncios.count > index {
let anuncio = AnunciosService.instance.anuncios[index]
let rowsToLoadFromBottom = 5;
let rowsLoaded = AnunciosService.instance.anuncios.count
if (!self.fetchingMore && (index >= (rowsLoaded - rowsToLoadFromBottom))) {
let totalRows = AnunciosService.instance.anunciosCount
let remainingAnunciosToLoad = totalRows - rowsLoaded;
if (remainingAnunciosToLoad > 0) {
self.loadMoreAnuncios()
}
}
cell.configureCell(anuncio: anuncio)
let checkValue = Double(anuncio.user.nota)!
if checkValue < 1.0 {
cell.notaView.isHidden = true
}else{
cell.notaView.isHidden = false
}
if anuncio.destaque {
cell.destaque.isHidden = false
} else {
cell.destaque.isHidden = true
}
if anuncio.status == 0 {
if cell.imgAnuncio.image != nil {
Noir(originalImage: cell.imgAnuncio)
}
cell.sold_out.isHidden = false
cell.selectionStyle = .none
cell.isUserInteractionEnabled = false;
} else {
cell.sold_out.isHidden = true
cell.isUserInteractionEnabled = true;
cell.selectionStyle = .default
}
}
return cell
}
}

How to make tableView(cellForRowAtIndexPath) with multiple UITableViewCell readable?

I have UITableView with multiple UITableViewCell, every cell have a different design and high, the problem I have that now the method tableView(cellForRowAtIndexPath) look so weird and unreadable and I don't know if this is the true and the good practice implementation for the case.
My method :
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if(indexPath.section == 0){ // linked news item
let cellIdentifier = "linkedNewsTableViewCell";
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! LinkedNewsTableViewCell;
let linked_news = LinkedNews[indexPath.row];
cell.newTitle.text = linked_news.news_title;
return cell;
}else if(indexPath.section > 1 && indexPath.row == 0 && indexPath.section != sections.count+2){ // section header item
let cellIdentifier = "sectionHeaderTableViewCell";
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! SectionHeaderTableViewCell;
let sec = sections[indexPath.section-2];
cell.lblSectionTitle.text = sec.section_name;
cell.backgroundColor = Constants.Colors.lightGray;
return cell;
}else if(indexPath.section == 2+sections.count){ // all rights reserved item
let cellIdentifier = "allRightsReservedTableViewCell";
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! AllRightsReservedTableViewCell;
cell.backgroundColor = Constants.Colors.lightGray;
return cell;
}else if(indexPath.section == 1){ // slider news item
let cellIdentifier = "newsTableViewCell";
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! NewsTableViewCell;
cell.imgVideo.hidden = true;
let newsItem = SliderNews[indexPath.row];
cell.txtNews.text = newsItem.news_title;
cell.lblTime.text = Utilities.timeAgoSinceDate(NSDate(timeIntervalSince1970:newsItem.createdstamp!), numericDates: false);
do{
let isSaved = try DBManger.sharedInstance.isSaved(String(newsItem.news_id!));
cell.isSaved = isSaved;
cell.news = newsItem;
if(isSaved == true){
cell.btnSave.setImage(UIImage(named: "ic_bookmark_blue"), forState: .Normal);
}else{
cell.btnSave.setImage(UIImage(named: "ic_bookmark"), forState: .Normal);
}
}catch{
}
if(SliderNews.count-1 == indexPath.row){
cell.buttomLine.hidden = true;
}else{
cell.buttomLine.hidden = false;
}
let image = cell.imgNews.getImage(newsItem.image!, timestamp: String(newsItem.createdstamp!), size: "228", qualty: "70");
cell.imgNews.loadImage(image,contentMode: .ScaleToFill)
cell.lblType.text = newsItem.section_name;
cell.backgroundColor = Constants.Colors.lightGray;
return cell;
}else{ // section news item
let sec = sections[indexPath.section-2];
if(indexPath.row == sec.news.count+1){
let cellIdentifier = "moreNewsTableViewCell";
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! MoreNewsTableViewCell;
cell.lblSectionName.text = "المزيد من \(sec.section_name!)";
cell.backgroundColor = Constants.Colors.lightGray;
return cell;
}
let cellIdentifier = "newsTableViewCell";
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! NewsTableViewCell;
cell.imgVideo.hidden = true;
let newsItem = sec.news[indexPath.row-1];
cell.txtNews.text = newsItem.news_title;
cell.lblTime.text = Utilities.timeAgoSinceDate(NSDate(timeIntervalSince1970:newsItem.createdstamp!), numericDates: false);
cell.lblType.text = sec.section_name;
if(sec.news.count == indexPath.row){
cell.buttomLine.hidden = true;
}else{
cell.buttomLine.hidden = false;
}
let image = cell.imgNews.getImage(newsItem.image!, timestamp: String(newsItem.createdstamp!), size: "228", qualty: "70");
cell.imgNews.loadImage(image,contentMode: .ScaleToFill)
cell.backgroundColor = Constants.Colors.lightGray;
do{
let isSaved = try DBManger.sharedInstance.isSaved(String(newsItem.news_id!));
cell.isSaved = isSaved;
cell.news = newsItem;
if(isSaved == true){
cell.btnSave.setImage(UIImage(named: "ic_bookmark_blue"), forState: .Normal);
}else{
cell.btnSave.setImage(UIImage(named: "ic_bookmark"), forState: .Normal);
}
}catch{
}
return cell;
}
}
After playing around with your code, you have a few issues thats needs to be resolved before the code can look much better:
1. You need a model that reflects your tableView data source , it should look something like:
let currentSectionModel = self.sections[indexPath.section]
let currentRowModel = currentSectionModel[]
and then you can use something more generic with your cells to set the model object:
cell.setRowModel(currentRowModel)
2. Your if statements that decides witch section to present, are very complicated,
for example this line:
if indexPath.section > 1 && indexPath.row == 0 && indexPath.section != sections.count+2 {
You have to find a better logic for this. Once you orgenize the model like I sad in section 1, This should look much more clear and you can change it to a switch statement, that questions an enum.
3. All cell logic, I prefer to do Inside the cell itself, for cleaner viewController, I've done so at the example code at the end.
4. Don't use strings for identifier, It can cause bugs. that's the reason I prefer to use an extension on UITableViewCell witch returns the class name as the identifier.
5. Don't use semi columns is swift.
6. All your cells should have a base class, that way you can use polymorphism when returning cells.
7. Once you have a model that represent the data source, you can use Switch statement instead of if statement.
This is the example code I've written, you have to work on your code a bit before it will compile. I'ts just a better practice example. (I didn't use switch statements only because your cases are too complexed to use a simple enum. Like I sad, I'ts something you have to work on, and make it more simple)
class BaseCellType: UITableViewCell {
}
class AllRightsReservedTableViewCell: BaseCellType {
// Your implementation
}
class LinkedNewsTableViewCell: BaseCellType {
func setLinkedNews(linedNews: LinkedNews) {
// Your implementation
}
}
class SectionHeaderTableViewCell: BaseCellType {
func setSectionModel(sectionModel: SectionModel) {
// Your implementation
}
}
class MoreNewsTableViewCell: BaseCellType {
func setSection(section: SectionModel) {
// Your implementation
}
}
class NewsTableViewCell: BaseCellType {
// Your implementation
}
class SectionsModel {
let rows: [RowModel]
}
extension UITableViewCell {
static var cellIdentifer: String {
get {
return String(self.dynamicType).componentsSeparatedByString("__").last!
}
}
}
enum SectionType: Int {
case AllRightsReserevedSection = 1, LinkedNewItem = 0
}
class ViewController: UIViewController {
var sections: [SectionsModel]!
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: BaseCellType
switch (section: indexPath.section,row: indexPath.row) {
case (SectionType.AllRightsReserevedSection.rawValue, _):
cell = tableView.dequeueReusableCellWithIdentifier(AllRightsReservedTableViewCell.cellIdentifer, forIndexPath: indexPath) as! AllRightsReservedTableViewCell;
case (SectionType.LinkedNewItem.rawValue, _):
cell = tableView.dequeueReusableCellWithIdentifier(LinkedNewsTableViewCell.cellIdentifer, forIndexPath: indexPath) as! LinkedNewsTableViewCell;
cell.setLinkedNews(LinkedNews[indexPath.row])
case let index where index.section > 1 , index.row == 0, index.section != secrion+2:
cell = tableView.dequeueReusableCellWithIdentifier(SectionHeaderTableViewCell.cellIdentifer, forIndexPath: indexPath) as! SectionHeaderTableViewCell
cell.setSectionModel(sections[indexPath.section-2])
case let index where index.section == section.count + 2:
cell = tableView.dequeueReusableCellWithIdentifier(AllRightsReservedTableViewCell.cellIdentifer, forIndexPath: indexPath) as! AllRightsReservedTableViewCell;
case let index where index.row == (sec.news.count + 1) :
cell = tableView.dequeueReusableCellWithIdentifier(MoreNewsTableViewCell.cellIdentifer, forIndexPath: indexPath) as! MoreNewsTableViewCell;
cell.setSection(sections[indexPath.section-2])
default:
cell = tableView.dequeueReusableCellWithIdentifier(NewsTableViewCell.cellIdentifer, forIndexPath: indexPath) as! NewsTableViewCell;
cell.setNewsItem(sec.news[indexPath.row-1])
}
}
return cell
}
Try this one
func makeBasicTableCell(title:String,details:String,indexPath:NSIndexPath) -> CustomHeaderCell{
let cell = tableProfile.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomHeaderCell
cell.titleLable.text = title
cell.detLable.text = details
return cell
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var tblCell: UITableViewCell!
tableView.registerNib(UINib(nibName: "profile_details", bundle: nil), forCellReuseIdentifier: "cell")
if indexPath.section == 0 {
switch(indexPath.row) {
case 0:
return makeBasicTableCell("Text1", details: "TextDetail1", indexPath: indexPath)
case 1:
return makeBasicTableCell("Text2", details: "TextDetail2", indexPath: indexPath)
case 2:
return makeBasicTableCell("Text3", details: "TextDetail3", indexPath: indexPath)
case 3:
return makeBasicTableCell("Text4", details: "TextDetail4", indexPath: indexPath)
default:
return makeBasicTableCell("", details: "", indexPath: indexPath)
}
} else if indexPath.section == 1 {
switch(indexPath.row) {
case 0:
return makeBasicTableCell("Text5", details: "TextDetail5", indexPath: indexPath)
case 1:
return makeBasicTableCell("Text6", details: "TextDetail6", indexPath: indexPath)
case 2:
return makeBasicTableCell("Text7", details: "TextDetail7", indexPath: indexPath)
default:
return makeBasicTableCell("", details: "", indexPath: indexPath)
}
}
return tblCell
}
In your cellForRowAtIndexPath -> *Objective-C
if(your first condition){
static NSString *cellIdentifier = #"cell";
MANewsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
tableView.rowHeight=30;
}else if(second condition ){
static NSString *cellIdentifier = #"cell1";
MANewsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
tableView.rowHeight=40;
}else
{
static NSString *cellIdentifier = #"cell2";
MANewsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
tableView.rowHeight=50;
}
I hope I help you.

Bad performance when presenting modally over uicollectionviewcontroller on iPad

in have a simple uicollectionviewcontroller with some simpel views in. In the UINavigationBar i have a button, when pressed presents modally (as formsheet) segue to a navigation controller, with a tableview as rootview.
On iPhone, it all works well, but on iPad the animation when it presents and when the presented tableview scroll, is bad and have low fps.
How can this be?
Please tell what kind of information from my app is needed to help me.
I am working in swift, iOS 8.3
UPDATE:
Okay, so i got 8 different kinds of prototypecells in my tableview, all with auto-layout in my storyboard. I have a subclass for each of them with IBOutlets.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (indexPath.section == 0) {
if indexPath.row == 0 {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.CalendarUnitWeekOfYear, fromDate: NSDate())
let cell = tableView.dequeueReusableCellWithIdentifier("weekCell", forIndexPath: indexPath) as! WeekChooserTableViewCell
cell.stepper.value = Double(components.weekOfYear)
cell.weekNumber.text = String(components.weekOfYear)
return cell
} else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCellWithIdentifier("customerCell", forIndexPath: indexPath) as! CustomerTableViewCell
cell.customerTextField.tag = "\(indexPath.row+1)\(indexPath.section+1)".toInt()!
cell.customerTextField.delegate = self
return cell
}
} else if indexPath.section > 0 && indexPath.section <= 5 {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("hourpayCell", forIndexPath: indexPath) as! HourpayTableViewCell
if arrayOfHourpay[indexPath.section-1] == 9999999999 {
cell.hourpayTextField.text = ""
} else {
cell.hourpayTextField.text = String("\(arrayOfHourpay[indexPath.section-1])")
}
cell.hourpayTextField.tag = "\(indexPath.row+1)\(indexPath.section+1)".toInt()!
cell.hourpayTextField.delegate = self
return cell
} else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCellWithIdentifier("casepayCell", forIndexPath: indexPath) as! CasepayTableViewCell
if arrayOfCasepay[indexPath.section-1] == 9999999999 {
cell.casepayTextField.text = ""
} else {
cell.casepayTextField.text = String("\(arrayOfCasepay[indexPath.section-1])")
}
cell.casepayTextField.tag = "\(indexPath.row+1)\(indexPath.section+1)".toInt()!
cell.casepayTextField.delegate = self
return cell
} else if indexPath.row == 2 {
let cell = tableView.dequeueReusableCellWithIdentifier("machinepayCell", forIndexPath: indexPath) as! MachinepayTableViewCell
if arrayOfMachinepay[indexPath.section-1] == 9999999999 {
cell.machinepayTextField.text = ""
} else {
cell.machinepayTextField.text = String("\(arrayOfMachinepay[indexPath.section-1])")
}
cell.machinepayTextField.tag = "\(indexPath.row+1)\(indexPath.section+1)".toInt()!
cell.machinepayTextField.delegate = self
return cell
} else if indexPath.row == 3 {
let cell = tableView.dequeueReusableCellWithIdentifier("daycommentCell", forIndexPath: indexPath) as! DayCommentTableViewCell
cell.textView?.tag = "\(indexPath.row+1)\(indexPath.section+1)".toInt()!
cell.textView?.text = arrayOfDayComments[indexPath.section-1]
return cell
}
} else if indexPath.section == 6 {
if indexPath.row + 1 == rowsInMaterialSection {
let cell = tableView.dequeueReusableCellWithIdentifier("addMaterialCell", forIndexPath: indexPath) as! AddNewMaterialTableViewCell
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("materialTextfieldCell", forIndexPath: indexPath) as! MaterialTextfieldTableViewCell
cell.MaterialTextField.text = arrayOfMaterials[indexPath.row]
cell.MaterialTextField.tag = "\(indexPath.row+1)\(indexPath.section+1)".toInt()!
cell.MaterialTextField.delegate = self
return cell
}
}
let cell = tableView.dequeueReusableCellWithIdentifier("daycommentCell", forIndexPath: indexPath) as! DayCommentTableViewCell
return cell
}

Resources