How to use multiple tableviews by using Multiple custom class - ios

I have xib files there I used create multiple table with multiple custom xib cell, but I got the problem while load the multiple custom cell. i am getting error on code of cell rowat indexpath...i dont know how to do that with multiple tableview with multiple custom cell
any one help me to solve this issues
Thanks in Advance
func TablecellRegisternib() {
self.Hight_table.register(UINib(nibName: "tableviewcellTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
self.weight_table.register(UINib(nibName: "tableviewcellTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
self.Gender_table.register(UINib(nibName: "tableviewcellTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
self.Weekday_table.register(UINib(nibName: "tableviewcellTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
self.Gym_tableview.register(UINib(nibName: "GymTableCell", bundle: nil), forCellReuseIdentifier: "cell1")
self.Sports_tableview.register(UINib(nibName: "SpotsTableCell", bundle: nil), forCellReuseIdentifier: "cell2")
self.AdditioanlSports_tableview.register(UINib(nibName: "AdditioanlSpotsTableCell", bundle: nil), forCellReuseIdentifier: "cell3")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of items in the sample data structure.
var count:Int?
if tableView == self.weight_table {
count = WightUnitArray.count
}
if tableView == self.Hight_table {
count = HightUnitArray.count
}
if tableView == self.Weekday_table {
count = WeekdayArray.count
}
if tableView == self.Gender_table {
count = GenderArray.count
}
if tableView == self.Sports_tableview {
count = SportsArray.count
}
if tableView == self.AdditionalSports_tableview {
count = AdditionalSportsArray.count
}
return count!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == self.weight_table {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! tableviewcellTableViewCell
cell.detail_lbl.text=WightUnitArray[indexPath.row]
cell.selectionStyle = UITableViewCellSelectionStyle.none;
cell.detail_lbl.font = UIFont(name:"Roboto-Regular", size:13)
cell.detail_lbl.adjustsFontSizeToFitWidth = true
if (selectedIndex == indexPath as NSIndexPath?) {
cell.radi_btn.setImage(UIImage(named: "radio_btn_active.png"),for:UIControlState.normal)
} else {
cell.radi_btn.setImage(UIImage(named: "radio_btn.png"),for:UIControlState.normal)
}
}
if tableView == self.Hight_table {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! tableviewcellTableViewCell
cell.detail_lbl.text=HightUnitArray[indexPath.row]
cell.selectionStyle = UITableViewCellSelectionStyle.none;
cell.detail_lbl.font = UIFont(name:"Roboto-Regular", size:13)
cell.detail_lbl.adjustsFontSizeToFitWidth = true
if (selectedIndex == indexPath as NSIndexPath?) {
cell.radi_btn.setImage(UIImage(named: "radio_btn_active.png"),for:UIControlState.normal)
} else {
cell.radi_btn.setImage(UIImage(named: "radio_btn.png"),for:UIControlState.normal)
}
}
if tableView == self.Weekday_table {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! tableviewcellTableViewCell
cell.detail_lbl.text=WeekdayArray[indexPath.row]
cell.selectionStyle = UITableViewCellSelectionStyle.none;
cell.detail_lbl.font = UIFont(name:"Roboto-Regular", size:13)
cell.detail_lbl.adjustsFontSizeToFitWidth = true
if (selectedIndex == indexPath as NSIndexPath?) {
cell.radi_btn.setImage(UIImage(named: "radio_btn_active.png"),for:UIControlState.normal)
} else {
cell.radi_btn.setImage(UIImage(named: "radio_btn.png"),for:UIControlState.normal)
}
}
if tableView == self.Gender_table {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! tableviewcellTableViewCell
cell.detail_lbl.text=GenderArray[indexPath.row]
cell.selectionStyle = UITableViewCellSelectionStyle.none;
cell.detail_lbl.font = UIFont(name:"Roboto-Regular", size:13)
cell.detail_lbl.adjustsFontSizeToFitWidth = true
if (selectedIndex == indexPath as NSIndexPath?) {
cell.radi_btn.setImage(UIImage(named: "radio_btn_active.png"),for:UIControlState.normal)
} else {
cell.radi_btn.setImage(UIImage(named: "radio_btn.png"),for:UIControlState.normal)
}
}
if tableView == self.Gym_tableview {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! GymTableCell
var GymDict = GymtableArray[indexPath.row]
cell.sportlbl!.text = GymDict["name"] as? String
cell.sportlbl?.adjustsFontSizeToFitWidth = true
cell.sportlbl?.font = UIFont(name:"Roboto-Regular", size:13)
return cell
}
if tableView == self.Sports_tableview {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell3") as! SportsTableCell
var SportsDict = SportsArray[indexPath.row]
cell.sportlbl1!.text = SportsDict["name"] as? String
cell.sportlbl1?.adjustsFontSizeToFitWidth = true
cell.sportlbl1?.font = UIFont(name:"Roboto-Regular", size:13)
return cell
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == self.weight_table {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
let row = indexPath.row
selectedIndex = indexPath as NSIndexPath?
let weightstring = (WightUnitArray[row])
if( weightstring != "Pound")
{
self.WeightUnitTabletxt.text = "kg"
}
else{
self.WeightUnitTabletxt.text = "lbs"
}
self.Weight_View.isHidden = true
tableView.reloadData()
}
if tableView == self.Hight_table {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
let row = indexPath.row
selectedIndex = indexPath as NSIndexPath?
let Hightstr = (HightUnitArray[row])
if( Hightstr != "Feet")
{
self.HeightUnitTabletxt.text = "m"
}
else{
self.HeightUnitTabletxt.text = "ft"
}
self.Hight_view.isHidden = true
tableView.reloadData()
}
if tableView == self.Weekday_table {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
let row = indexPath.row
selectedIndex = indexPath as NSIndexPath?
self.FirstDayofWeek_txt.text = (WeekdayArray[row])
self.FirstdayoftheWeek_view.isHidden = true
tableView.reloadData()
}
if tableView == self.Gender_table {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
let row = indexPath.row
selectedIndex = indexPath as NSIndexPath?
self.gender_txt.text = (GenderArray[row])
self.Genderview.isHidden = true
tableView.reloadData()
}
}

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
}
}

How to handle two table views in single view controller by using xibs as cell

I am trying to use the segment controller with 3 segments. If I click on first segment, I should get one tableview. When I click on second segment, I should get second tableview and for third segment I should get 3rd table view. Here I am using XIB's for tableview cell. I tried something but I am not getting any data in the table. The table is loading. But the cell is not loading. I am giving my code below. If any one helps me, would be very great. Thanks in advance.
var arr1 = ["1","2","3","4"]
var imagesarray = [UIImage(named: "11.png")!, UIImage(named: "22.png")!, UIImage(named: "33.png")!,UIImage(named: "11.png")!,UIImage(named: "22.png")!, UIImage(named: "33.png")!]
override func viewDidLoad() {
super.viewDidLoad()
view_track.isHidden = false
view_watch.isHidden = true
view_ebooks.isHidden = true
table_track.register(UINib(nibName: "ProgramMListenTableViewCell", bundle: nil), forCellReuseIdentifier: "ProgramMListenTableViewCell")
table_watch.register(UINib(nibName: "ProgramMWatchTableViewCell", bundle: nil), forCellReuseIdentifier: "ProgramMWatchTableViewCell")
table_watch.register(UINib(nibName: "ProgramEbooksTableViewCell", bundle: nil), forCellReuseIdentifier: "ProgramEbooksTableViewCell")
table_ebooks.delegate = self
table_ebooks.dataSource = self
table_track.delegate = self
table_track.dataSource = self
table_watch.delegate = self
table_watch.dataSource = self
self.navigationController?.setNavigationBarHidden(true, animated: false)
}
#IBAction func Segment(_ sender: Any) {
switch segment_program.selectedSegmentIndex
{
case 0:
view_track.isHidden = false
view_watch.isHidden = true
view_ebooks.isHidden = true
self.table_track.reloadData()
break
case 1:
view_track.isHidden = true
view_watch.isHidden = false
view_ebooks.isHidden = true
self.table_watch.reloadData()
name_program.text = "Videos"
break
case 2:
view_track.isHidden = true
view_watch.isHidden = true
view_ebooks.isHidden = false
self.table_ebooks.reloadData()
name_ebooks.text = "Ebooks"
break
default:
break
}
}
}
extension ProgramMListenViewController: UITableViewDataSource,UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == table_track{
return self.arr1.count
}else if tableView == table_watch{
return self.imagesarray.count
}else{
return self.arr1.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == table_track{
let cell = table_track.dequeueReusableCell(withIdentifier: "ProgramMListenTableViewCell") as! ProgramMListenTableViewCell
}else if tableView == table_watch{
let cell = table_watch.dequeueReusableCell(withIdentifier: "ProgramMWatchTableViewCell") as! ProgramMWatchTableViewCell
cell.img_watch.image = imagesarray[indexPath.row]
}else if tableView == table_ebooks{
let cell = table_ebooks.dequeueReusableCell(withIdentifier: "ProgramEbooksTableViewCell") as! ProgramEbooksTableViewCell
cell.image_ebooks.image = imagesarray[indexPath.row]
}
return UITableViewCell()
}
}
You have to return your cell, instead of always returning UITableViewCell()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == table_track{
let cell = table_track.dequeueReusableCell(withIdentifier: "ProgramMListenTableViewCell") as! ProgramMListenTableViewCell
return cell
}else if tableView == table_watch{
let cell = table_watch.dequeueReusableCell(withIdentifier: "ProgramMWatchTableViewCell") as! ProgramMWatchTableViewCell
cell.img_watch.image = imagesarray[indexPath.row]
return cell
}else if tableView == table_ebooks{
let cell = table_ebooks.dequeueReusableCell(withIdentifier: "ProgramEbooksTableViewCell") as! ProgramEbooksTableViewCell
cell.image_ebooks.image = imagesarray[indexPath.row]
return cell
}
return UITableViewCell()
}
As mentioned before you need to return the respective UITableViewCell, depending on the table in order for it to be shown. You should watch for errors in dequeueReusableCell(), thus I recommend the following implementation:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var returnCell = UITableViewCell()
if tableView == table_track{
guard let cell = table_track.dequeueReusableCell(withIdentifier: "ProgramMListenTableViewCell") as? ProgramMListenTableViewCell else {
print("Error getting cell as ProgramMListenTableViewCell")
return returnCell
}
/*Customize your cell*/
returnCell = cell
}else if tableView == table_watch{
guard let cell = table_watch.dequeueReusableCell(withIdentifier: "ProgramMListenTableViewCell") as? ProgramMWatchTableViewCell else {
print("Error getting cell as ProgramMWatchTableViewCell")
return returnCell
}
/*Customize your cell*/
cell.img_watch.image = imagesarray[indexPath.row]
returnCell = cell
}else if tableView == table_ebooks{
guard let cell = table_ebooks.dequeueReusableCell(withIdentifier: "ProgramMListenTableViewCell") as? ProgramEbooksTableViewCell else {
print("Error getting cell as ProgramEbooksTableViewCell")
return returnCell
}
cell.image_ebooks.image = imagesarray[indexPath.row]
returnCell = cell
}
return returnCell
}
This way you have a safe way of getting the correct type of your cell, editing it and returning it to the corresponding table.

Only Single cell expands at a time in UITableViewCell in swift3

I am implementing an expandable and collapsable table cell on the click of a button in the custom table cell. I have tried the following code but it expands only single cell at a time. That is if I click a cell it expands but if I click on another cell it expands and the already expanded cell collapses.
var selectedIndexPath: IndexPath?
func configure(cell: MyProposalCustomCell, forRowAtIndexPath indexPath: IndexPath) {
let pool = myProposalsDetails[indexPath.row]
cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = UIEdgeInsets.zero
cell.layoutMargins = UIEdgeInsets.zero
cell.proposalNumber.text = pool.proposalNumber
cell.pickUpLocation.text = pool.pickupLocation
cell.dropLocation.text = pool.dropLocation
cell.journeyType.text = pool.journeyType
cell.firstShiftOnwardTime.text = pool.firstPickupTime
cell.firstShiftReturnTime.text = pool.firstEndTime
if let numberOfInterests = pool.noOfInterest {
cell.numberOfInterest.text = String(numberOfInterests)
}
if let operatingDays = pool.operatingDays {
cell.daysOfOperation.attributedText = Utility.getProposedOperatingDays(operatingDays: operatingDays)
}
cell.expandCollapse.tag = indexPath.row
cell.expandCollapse.addTarget(self, action: #selector(expandTableCell(sender:)), for: .touchUpInside)
if selectedIndexPath == indexPath {
UIView.animate(withDuration: 0.3, animations: {
cell.backgroundColor = CustomColor.selectedBackground.color
cell.bottomView.backgroundColor = CustomColor.selectedBackground.color
cell.expandCollapse.setImage(UIImage(named: "collapse_arrow.png"), for: .normal)
if let proposedStartDate = pool.startDate {
let propStartDate = Date(timeIntervalSince1970: proposedStartDate)
cell.proposedStartDate.text = Utility.getFormattedDate(date: propStartDate)
cell.proposedStartDateTxt.text = NSLocalizedString("Proposed start date", comment: "")
}
cell.returnTime.alpha = 0.0
})
} else {
UIView.animate(withDuration: 0.3, animations: {
cell.backgroundColor = UIColor.white
cell.expandCollapse.setImage(UIImage(named: "down_arrow.png"), for: .normal)
cell.proposedStartDateTxt.text = NSLocalizedString("Journey type", comment: "")
cell.bottomView.backgroundColor = UIColor.white
cell.proposedStartDate.text = pool.journeyType
cell.returnTime.isHidden = false
})
}
}
This is the expandable button action:
func expandTableCell(sender: UIButton) {
let indexPath = IndexPath(row: sender.tag, section: 0)
if selectedIndexPath == indexPath {
selectedIndexPath = nil
} else {
let previousSelIndex = selectedIndexPath
selectedIndexPath = indexPath
if let previousSelectedIndexPath = previousSelIndex {
if tripStatus.tripType != .splitShift {
if let previousSelectedCell = myProposals.cellForRow(at: previousSelectedIndexPath) as? MyProposalCustomCell {
configure(cell: previousSelectedCell, forRowAtIndexPath: previousSelectedIndexPath)
}
} else {
if let previousSelectedCell = myProposals.cellForRow(at: previousSelectedIndexPath) as? MyProposalSplitShiftCell {
configureSplitShift(cell: previousSelectedCell, forRowAtIndexPath: previousSelectedIndexPath)
}
}
}
}
updateSelectedCell(indexPath: indexPath)
myProposals.beginUpdates()
myProposals.endUpdates()
}
func updateSelectedCell(indexPath: IndexPath) {
if tripStatus.tripType != .splitShift {
if let selectedCell = myProposals.cellForRow(at: indexPath) as? MyProposalCustomCell {
configure(cell: selectedCell, forRowAtIndexPath: indexPath)
}
} else {
if let selectedCell = myProposals.cellForRow(at: indexPath) as? MyProposalSplitShiftCell {
configureSplitShift(cell: selectedCell, forRowAtIndexPath: indexPath)
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let headingHeight: CGFloat = 128
let detailsHeight: CGFloat = 80
let splitShiftDetailsHeight: CGFloat = 215
switch tripStatus.tripType {
case .oneWayTrip, .roundTrip:
if selectedIndexPath != nil && indexPath.compare(selectedIndexPath! as IndexPath) == ComparisonResult.orderedSame {
return headingHeight + detailsHeight
}
return headingHeight
case .splitShift:
if selectedIndexPath != nil && indexPath.compare(selectedIndexPath! as IndexPath) == ComparisonResult.orderedSame {
return headingHeight + splitShiftDetailsHeight
}
return headingHeight
}
}
I want to get multiple cells to be expanded. How to achieve this?
This is very straight forward, instead of taking selectedIndexPath try to keep one variable in your custom UITableViewCell class something like,
class ExpandableCell: UITableViewCell {
var isExpanded: Bool = false
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
#IBAction func moreButtonTapped(_ sender: Any) {
}
}
And then try to toggle the isExpanded boolean flag, and try to perform your func updateSelectedCell(indexPath: IndexPath) {} action.

Different UITableViewCells overlapping

I have a UITableView with 3 prototype cells and 3 custom cell classes:
FriendCell
FriendRequestCell and AddFriendCell.
Initialized, the table displays Friends.
If there are any FriendRequests, it displays them in the section above Friends.
If there are no FriendRequests, it only displays Friends.
However, I also have a UISearchBar that searches for users and when it has results, should return AddFriendCells and reload the table.
Instead, I get this:
Code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if searching == true {
if let cell = tableView.dequeueReusableCellWithIdentifier("AddFriendCell", forIndexPath: indexPath) as? AddFriendCell {
let resultCell = userResults[indexPath.row]
cell.configureCell(resultCell)
}
} else {
if friendRequests.isEmpty || (indexPath.section == 1) {
if let cell = tableView.dequeueReusableCellWithIdentifier("FriendCell", forIndexPath: indexPath) as? FriendCell {
let friendCell = friends[indexPath.row]
cell.configureCell(friendCell)
}
} else {
if (indexPath.section == 0) {
if let cell = tableView.dequeueReusableCellWithIdentifier("FriendRequestCell", forIndexPath: indexPath) as? FriendRequestCell {
let friendRequestCell = friendRequests[indexPath.row]
cell.configureCell(friendRequestCell)
}
}
}
}
return FriendCell()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if searching == true {
return 1
} else {
return friendsDataSource.count
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searching == true {
return userResults.count
} else {
return friendsDataSource[section].count
}
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if searching == true {
return nil
} else {
if friendsDataSource.count > 1 {
if section == 0 {
return "Friend Requests"
} else if section == 1 {
return "Friends"
}
} else {
return "Friends"
}
return "Friends"
}
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if searching == true {
return 0
} else {
return 25
}
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searching = true
searchBar.resignFirstResponder()
userResults = [UserProfile]()
activitySpinner.startAnimating()
if let searchText = searchBar.text {
let userProfileQuery = PFQuery(className: "UserProfile")
userProfileQuery.whereKey("username", containsString: searchText)
userProfileQuery.findObjectsInBackgroundWithBlock({ resultArray, error in
if error != nil {
print("there's been an error searching for users: \(error)")
} else if let resultArray = resultArray {
print("number of results: \(resultArray.count)")
self.parseResults = resultArray
for userProfile in resultArray {
let username = userProfile["username"] as! String
let profilePicUrl = userProfile["profilePicUrl"] as! String
let parseObjectId = userProfile.objectId!
let newProfile = UserProfile(username: username, profilePicUrl: profilePicUrl, parseObjectId: parseObjectId)
self.userResults.append(newProfile)
}
self.tableView.reloadData()
self.activitySpinner.stopAnimating()
}
})
}
}
Any ideas on the root of the problem?
OK, here is the code for multiple types of cell:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if searching == true {
let cell = tableView.dequeueReusableCellWithIdentifier("AddFriendCell", forIndexPath: indexPath) as! AddFriendCell
// ...configure your cell...
return cell
}
else{
if friendRequests.isEmpty || (indexPath.section == 1) {
let cell = tableView.dequeueReusableCellWithIdentifier("FriendCell", forIndexPath: indexPath) as! FriendCell
// ...configure your cell...
return cell
}
else{
if (indexPath.section == 0) {
let cell = tableView.dequeueReusableCellWithIdentifier("FriendRequestCell", forIndexPath: indexPath) as! FriendRequestCell
// ...configure your cell...
return cell
}
else {
// Decide what to do if section is NOT 0. If this CAN happen
// and you don't have a cell type to return, it is a design flaw.
// don't add a adummy "return FriendCell()" as a fallback for a
// case that should never happen, to make the compiler happy.
// This type of error should be caught during development.
}
}
}
}
(See the comment paragraph on how to deal with the unsuported execution path)
Alternatively, you could declare cell as a var of type UITableViewCell outside of all if/else blocks, assign it to the appropriatey dequeued cell inside, (i.e., remove the let keyword if modifying the code above), and return it at the very end.
But you still need to make sure it is initialized before returning.
if the method findObjectsInBackgroundWithBlock is asynchronous, I think you can use self.tableView.reloadData() instead of dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
add self.tableView.rowHeight = 50
and you don't return your addfriendcell. you just return FriendsCell() at the last line. add the return cell.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if searching == true {
if let cell = tableView.dequeueReusableCellWithIdentifier("AddFriendCell", forIndexPath: indexPath) as? AddFriendCell {
let resultCell = userResults[indexPath.row]
cell.configureCell(resultCell)
return cell! //add the return
}
} else {
if friendRequests.isEmpty || (indexPath.section == 1) {
if let cell = tableView.dequeueReusableCellWithIdentifier("FriendCell", forIndexPath: indexPath) as? FriendCell {
let friendCell = friends[indexPath.row]
cell.configureCell(friendCell)
return cell! //add the return
}
} else {
if (indexPath.section == 0) {
if let cell = tableView.dequeueReusableCellWithIdentifier("FriendRequestCell", forIndexPath: indexPath) as? FriendRequestCell {
let friendRequestCell = friendRequests[indexPath.row]
cell.configureCell(friendRequestCell)
return cell! //add the return
}
}
}
}
return FriendCell()
}

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