UITableView Checkmark not appearing when selected - ios

I am using a UITableView on button click i am putting the tableview into edit mode I have added
tableView.allowMultiselectionduringedit = true
Here i am getting circles to select the table but no check mark is added when tapped. But code in didselectrow is getting executed
I have attached a picture
What should i change to get the rows selected
Code for didselect
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Did select Run")
if(isEditing){
let cell = chatTableView.cellForRow(at: indexPath)
cell?.setSelected(true, animated: true)
}else{
let groupMsg = groupMsgList[indexPath.row]
if(groupMsg.messageType == "file")
{
let fileNameString = groupMsg.fileOriginalName
if(fileNameString != nil){
let fileName: NSString = fileNameString! as NSString
let extention = fileName.pathExtension.lowercased()
switch extention {
case "jpg","png","jpeg":
if (groupMsg.senderUserId != LoginStatusInfo.userId){
let row = chatTableView.cellForRow(at: indexPath) as! PhotoReciveCell
chatTableView.beginUpdates()
row.downloadLabel.text = " Downloading... "
row.downloadLabel.sizeToFit()
row.downloadLabelConstraint.constant = 30.0
row.downloadLabel.layoutMargins = UIEdgeInsets(top: 2.0, left: 2.0, bottom: 2.0, right: 2.0)
downloadFileBackground(id: groupMsg.messageId!, fileName: groupMsg.message!, cellIndexPath: indexPath )
chatTableView.endUpdates()
}else{
let row = chatTableView.cellForRow(at: indexPath) as! PhotoSentCell
chatTableView.beginUpdates()
row.downloadLabel.text = " Downloading... "
row.downloadLabel.sizeToFit()
row.downloadLabelConstraint.constant = 30.0
row.downloadLabel.layoutMargins = UIEdgeInsets(top: 2.0, left: 2.0, bottom: 2.0, right: 2.0)
downloadFileBackground(id: groupMsg.messageId!, fileName: groupMsg.message!, cellIndexPath: indexPath )
chatTableView.endUpdates()
}
break
default :
if (groupMsg.senderUserId != LoginStatusInfo.userId){
let row = chatTableView.cellForRow(at: indexPath) as! FileRecieveCell
chatTableView.beginUpdates()
row.downloadStatusIndicator.isHidden = true
row.downloadingIndicator.alpha = 1.0
chatTableView.endUpdates()
}else{
let row = chatTableView.cellForRow(at: indexPath) as! FileSentCell
chatTableView.beginUpdates()
row.downloadStatusIndicator.isHidden = true
row.downloadingIndicator.alpha = 1.0
chatTableView.endUpdates()
}
downloadFileBackground(id: groupMsg.messageId!, fileName: groupMsg.fileOriginalName!, cellIndexPath: indexPath )
break
}
}
}
print(indexPath)
}
}
For CellatRow
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let groupMsg = groupMsgList[indexPath.row]
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressed(_:)))
groupId = groupMsg.groupId
//MARK: MessageType is textmessage
if (groupMsg.messageType == "message")
{
if (groupMsg.senderUserId != LoginStatusInfo.userId)
{
let cell : RecievedMessageCell = chatTableView.dequeueReusableCell(withIdentifier: "recieve") as! RecievedMessageCell
cell.name.text = groupMsg.senderDisplayName
cell.message.text = groupMsg.message
cell.time.text = groupMsg.dateSent!
// cell.message.sizeToFit()
cell.receiveMessageView.tag = indexPath.row
cell.receiveMessageView.addGestureRecognizer(longPressGesture)
return cell
}
else
{
let cell : SentMessageCell = chatTableView.dequeueReusableCell(withIdentifier: "send") as! SentMessageCell
// cell.sentMessageView.roundCorners(corners: [.topLeft,.topRight,.bottomLeft], radius: 20)
// cell.sentMessageView.layer.masksToBounds = false
cell.sentMessageView.layer.cornerRadius = 10
cell.message.text = groupMsg.message
cell.time.text = groupMsg.dateSent!
cell.messageStatus.isHidden = false
cell.messageStatus.text = groupMsg.status
// cell.message.sizeToFit()
cell.sentMessageView.tag = indexPath.row
cell.sentMessageView.addGestureRecognizer(longPressGesture)
return cell
}
}
//MARK: Message type is Banner
else if (groupMsg.messageType == "banner") {
let cell : BotBanner = chatTableView.dequeueReusableCell(withIdentifier: "botBanner") as! BotBanner
hasBanner = true
scrollToIndex = indexPath.row
return cell
}
//MARK: Message type is File
else{
if (groupMsg.senderUserId != LoginStatusInfo.userId)
{
//MARK: File Recived
let fileNameString = groupMsg.fileOriginalName
if(fileNameString != nil){
let fileName: NSString = fileNameString! as NSString
let extention = fileName.pathExtension.lowercased()
let cell : FileRecieveCell = chatTableView.dequeueReusableCell(withIdentifier: "fileRecieve") as! FileRecieveCell
let fileUrl = self.getImageURL(forFileName: fileNameString!)
if(fileUrl == nil){
cell.downloadStatusIndicator.image = #imageLiteral(resourceName: "fileDonwloadBlack")
}else{
cell.downloadStatusIndicator.image = #imageLiteral(resourceName: "downloadedBlack")
}
cell.downloadStatusIndicator.isHidden = false
cell.downloadingIndicator.alpha = 0.0
cell.receiveFileView.layer.cornerRadius = 10
cell.name.text = groupMsg.senderDisplayName
cell.message.text = groupMsg.message
cell.time.text = groupMsg.dateSent!
cell.fileIcon.image = returnImage(fileName:groupMsg.message!)
cell.receiveFileView.isUserInteractionEnabled = true
cell.receiveFileView.addGestureRecognizer(longPressGesture)
cell.receiveFileView.tag = indexPath.row
return cellname.text = groupMsg.senderDisplayName
cell.message.text = groupMsg.message
cell.time.text = groupMsg.dateSent!
cell.fileIcon.image = returnImage(fileName:groupMsg.message!)
cell.receiveFileView.isUserInteractionEnabled = true
cell.receiveFileView.addGestureRecognizer(longPressGesture)
cell.receiveFileView.tag = indexPath.row
return cell
}
}
else
{
let cell : FileSentCell = chatTableView.dequeueReusableCell(withIdentifier: "fileSend") as! FileSentCell
let fileUrl = self.getImageURL(forFileName: fileNameString!)
if(fileUrl == nil){
cell.downloadStatusIndicator.image = #imageLiteral(resourceName: "fileDownloadWhite")
}else{
cell.downloadStatusIndicator.image = #imageLiteral(resourceName: "downloadedWhite")
}
cell.downloadStatusIndicator.isHidden = false
cell.downloadingIndicator.alpha = 0.0
cell.sendFileView.layer.cornerRadius = 10
cell.name.text = groupMsg.senderDisplayName
cell.message.text = groupMsg.message
cell.time.text = groupMsg.dateSent!
cell.fileStatus.text = groupMsg.status
cell.fileIcon.image = returnImage(fileName:groupMsg.message!)
cell.sendFileView.tag = indexPath.row
cell.sendFileView.addGestureRecognizer(longPressGesture)
cell.sendFileView.isUserInteractionEnabled = true
return cell
}
}
}
}

Solved!
My Mistake was i needed to add cell.setSelectionStype = .default in cellForAtRow

Tableview use dequeueReusableCell , so you can
cell?.setSelected(true, animated: true)
When you scroll tableview , the same cell - reusable from a cell will is selected -> wrong.
In GroupMessage model add property: isSelected . and set
isSelected = true
self.tableview.reloadrowatindexpath ....
when didselected
In cellForRowAt indexPath
If groupMsg.isSelected{
cell?.setSelected(true, animated: true)
}else{
cell?.setSelected(false, animated: true)
}
OR create a NSMutableArray - selectedMessage to hold message selected didSelected add/remove groupmessage in selectedMessage
In cellForRowAt indexPath check selectedMessage contains groupmessage - setSelected = true or no

Related

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?

In table view cell data was not loading in screen during it's launch?

In this i am having three sections in a table view in which first section will have addresses and radio buttons if i click on radio button it will active and the particular address will be posting depending on the address selection the third section needs to call the api and load the data in the second table view which is present in third section here the problem is during loading for first time when app launched in simulator it is not loading the third section cell data can any one help me how to reduce the error ?
here is the code for table view class
func numberOfSections(in tableView: UITableView) -> Int
{
if ((addressSelected == true || checkIsPaymentRadioSelect == true) && selected == false) {
return 3
}else {
return 2
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
if ((addressSelected == true || checkIsPaymentRadioSelect == true) && selected == false) {
if (section == 0) {
return "SHIPPING ADDRESS"
}
else if (section == 2) {
return "SHIPPING METHOD"
}
else {
return ""
}
}
else {
if (section == 0) {
return "SHIPPING ADDRESS"
}
else{
return ""
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if (section == 0)
{
return shippingArray.count
}
else
{
return 1
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
if ((addressSelected == true || checkIsPaymentRadioSelect == true) && selected == false){
if (indexPath.section == 0){
return UITableViewAutomaticDimension
}
else if (indexPath.section == 1){
return 62
}
else {
print(height)
return CGFloat(height)
}
}
else{
if (indexPath.section == 0){
return UITableViewAutomaticDimension
}
else if (indexPath.section == 1){
return 62
}
else {
return 0
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath.section == 0)
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AddressTableViewCell
tableDetails.isHidden = false
activityIndicator.stopAnimating()
let arr = shippingArray[indexPath.row]
cell.deleteButton.tag = indexPath.row
cell.nameLabel.text = arr["name"] as? String
cell.addressLabel.text = arr["address"]as? String
let mobilenumber : Any = arr["number"] as AnyObject
cell.mobileNumberLabel.text = "\(mobilenumber)"
cell.radioButton.tag = indexPath.row
cell.editButton.tag = indexPath.row
cell.deleteButton.tag = indexPath.row
cell.editButton.isHidden = true
cell.deleteButton.isHidden = true
cell.radioButton.addTarget(self, action: #selector(selectRadioButton(_:)), for: .touchUpInside)
cell.deleteButton.addTarget(self, action: #selector(deleteAction(button:)), for: .touchUpInside)
let checkIndex = self.checkIsRadioSelect.index(of: indexPath.row)
if(checkIndex != nil){
cell.radioButton.isSelected = true
cell.editButton.isHidden = false
cell.deleteButton.isHidden = false
}
else
{
cell.radioButton.isSelected = false
cell.editButton.isHidden = true
cell.deleteButton.isHidden = true
}
if (checkIsPaymentRadioSelect == true){
let defaultvalue = arr["default"] as! Int
if defaultvalue == 1 {
cell.radioButton.isSelected = true
cell.editButton.isHidden = false
cell.deleteButton.isHidden = false
addressSelected = true
tableDetails.tableFooterView?.isHidden = false
}
}
return cell
}
else if (indexPath.section == 1){
let cell = tableView.dequeueReusableCell(withIdentifier: "addresscell", for: indexPath) as! CreateNewAddressTableViewCell
cell.newAddressButton.addTarget(self, action: #selector(newAddressAction(_:)), for: .touchUpInside)
return cell
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "shippingmethodcell", for: indexPath) as! MethodTableViewCell
cell.delegate = self
cell.boolDelegate = self
cell.shippingTableView.reloadData()
if shippingRadio == true {
cell.select = shippingRadio
cell.boolSelected()
cell.shippingmethodURL()
cell.shippingTableView.reloadData()
}
else{
cell.select = methodRadio
cell.shippingTableView.reloadData()
}
return cell
}
}
in this cell class i had got the api data and is passed to table view as shown in the code now i need to call api during cell selection of address can anyone help me how to clear the error or any alternative for this
var chekIndex:IndexPath?
var arrayss = [String:Any]()
var keys = [String]()
let urlString = "http://www.json-generator.com/api/json/get/bVgbyVQGmq?indent=2"
var delegate: CheckoutDelegate?
var heightConstant: Int?
var name = [String]()
var totalCount = 0
var radioSelected:Bool?
var radioSelection: Bool?
var boolDelegate: BoolValidationDelegate?
var select:Bool?
override func awakeFromNib() {
super.awakeFromNib()
radioSelection = false
self.shippingmethodURL()
shippingTableView.delegate = self
shippingTableView.dataSource = self
shippingTableView.rowHeight = UITableViewAutomaticDimension
shippingTableView.estimatedRowHeight = shippingTableView.rowHeight
// Initialization code
}
func paymentRadioAction(button : KGRadioButton) {
_ = button.center
let centralPoint = button.superview?.convert(button.center, to:self.shippingTableView)
let indexPath = self.shippingTableView.indexPathForRow(at: centralPoint!)
if button.isSelected {
} else{
chekIndex = indexPath
radioSelection = true
self.shippingTableView.reloadData()
self.boolDelegate?.boolvalidation(bool: radioSelection!)
}
}
func shippingmethodURL() {
guard let url = URL(string: self.urlString) else {return}
URLSession.shared.dataTask(with: url, completionHandler: {(data, response, error) -> Void in
if let data = data, let jsonObj = (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)) as? [String:Any] {
self.arrayss = jsonObj
self.keys = Array(jsonObj.keys)
for value in jsonObj.values {
if let array = value as? [[String:Any]] {
for element in array {
if (element["name"] as? String) != nil {
self.totalCount += 1
}
}
}
}
DispatchQueue.main.async {
self.shippingTableView.reloadData()
let sectionHeight = self.arrayss.count * 31
let cellHeight = self.totalCount * 44
self.shippingHeightConstraint.constant = CGFloat(sectionHeight + cellHeight)
self.heightConstant = Int(self.shippingHeightConstraint.constant)
self.delegate?.heightConstant(int: self.heightConstant!)
}
}
}).resume()
}
func numberOfSections(in tableView: UITableView) -> Int {
return arrayss.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.keys[section]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let key = self.keys[section]
let a :[Any] = arrayss[key] as! [Any]
return a.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "shippingCell", for: indexPath) as! ShippingMethodTableViewCell
let key = self.keys[indexPath.section]
var a :[Any] = arrayss[key] as! [Any]
var dictionary = a[indexPath.row] as! [String:Any]
let name = dictionary["name"]
let price = dictionary ["price"]
cell.methodLabel.text = name as? String
cell.priceLabel.text = price as? String
cell.radioButton.addTarget(self, action: #selector(paymentRadioAction(button:)), for: .touchUpInside)
if chekIndex == indexPath {
cell.radioButton.isSelected = true
} else {
cell.radioButton.isSelected = false
}
return cell
}
and the first time image loading is shown below
!enter image description here ]1
and if i select another radio button in first section it was working fine as expected and image is shown below

how to remove index path for the radio button in table view cell?

Here I am having a radio button after making radio button enable then the delete and edit buttons will appear after selecting delete the particular cell was deleting but the preceding row radio button was enabling how to avoid this any help ?
and here is the code for this
#IBAction func selectRadioButton(_ sender: KGRadioButton) {
let chekIndex = self.checkIsRadioSelect.index(of: sender.tag)
_ = self.checkIsButtonEnable.index(of: sender.tag)
if sender.isSelected {
} else{
if(chekIndex == nil){
self.checkIsRadioSelect.removeAll(keepingCapacity: false)
self.checkIsRadioSelect.append(sender.tag)
self.checkIsButtonEnable.removeAll(keepingCapacity: false)
self.checkIsButtonEnable.append(sender.tag)
self.tableDetails.reloadData()
self.addressSelected = true
tableDetails.tableFooterView?.isHidden = false
tableDetails.reloadData()
}
}
}
func deleteAction(button: UIButton) {
let buttonPosition = button.convert(CGPoint(), to: tableDetails)
let index = tableDetails.indexPathForRow(at: buttonPosition)
self.tableDetails.beginUpdates()
shippingArray.remove(at:(index?.row)!)
self.tableDetails.deleteRows(at: [index!], with: .top)
self.tableDetails.endUpdates()
tableDetails.tableFooterView?.isHidden = true
self.addressSelected = false
self.tableDetails.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath.section == 0)
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AddressTableViewCell
tableDetails.isHidden = false
myActivityIndicator.stopAnimating()
let arr = shippingArray[indexPath.row]
cell.deleteButton.tag = indexPath.row
cell.nameLabel.text = arr["name"] as? String
cell.addressLabel.text = arr["address"]as? String
let mobilenumber : Any = arr["number"] as AnyObject
cell.mobileNumberLabel.text = "\(mobilenumber)"
cell.radioButton.tag = indexPath.row
cell.editButton.tag = indexPath.row
cell.deleteButton.tag = indexPath.row
cell.editButton.isHidden = true
cell.deleteButton.isHidden = true
cell.deleteButton.addTarget(self, action: #selector(deleteAction(button:)), for: .touchUpInside)
let checkIndex = self.checkIsRadioSelect.index(of: indexPath.row)
if(checkIndex != nil){
cell.radioButton.isSelected = true
cell.editButton.isHidden = false
cell.deleteButton.isHidden = false
}
else
{
cell.radioButton.isSelected = false
cell.editButton.isHidden = true
cell.deleteButton.isHidden = true
}
return cell
}
Add two line in your delete method.
func deleteAction(button: UIButton) {
let buttonPosition = button.convert(CGPoint(), to: tableDetails)
let index = tableDetails.indexPathForRow(at: buttonPosition)
self.tableDetails.beginUpdates()
shippingArray.remove(at:(index?.row)!)
self.tableDetails.deleteRows(at: [index!], with: .top)
self.tableDetails.endUpdates()
tableDetails.tableFooterView?.isHidden = true
self.addressSelected = false
**let checkIndex = self.checkIsRadioSelect.index(of: button.tag)
self.checkIsRadioSelect.remove(at:checkIndex)**
self.tableDetails.reloadData()
}

Transferring UITableView Section to Another TableView

I am currently set up to transfer section 1 of my tableview to another tableView. This is done by moving the didSelectRow: rows. However, the issue is that when I attempt to move the section when every row is selected (and there is nothing in section 0) it crashes with an index is beyond bounds error.
I am using a boilerPlate code for my sectionHeaders due to section 1 header changing back to section 0 header when all items selected in section 1. I believe this is what is causing the index to be out of bounds error, but am not sure how to correct it.
My sections are set up as:
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
let numberOfSections = frc.sections?.count
return numberOfSections!
}
//Table Section Headers
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?{
let sectionHeader = "Items Needed - #\(frc.sections![section].numberOfObjects)"
let sectionHeader1 = "Items in Cart - #\(frc.sections![section].numberOfObjects)"
if (frc.sections!.count > 0) {
let sectionInfo = frc.sections![section]
if (sectionInfo.name == "0") {
return sectionHeader
} else {
return sectionHeader1
}
} else {
return nil
}
}
with my didSelectRow and cells as:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! SLTableViewCell
//assign delegate
cell.delegate = self
let items = frc.objectAtIndexPath(indexPath) as! List
cell.backgroundColor = UIColor.clearColor()
cell.tintColor = UIColor.grayColor()
cell.cellLabel.text = "\(items.slitem!) - Qty: \(items.slqty!)"
cell.cellLabel.font = UIFont.systemFontOfSize(25)
moveToPL.hidden = true
if (items.slcross == true) {
cell.accessoryType = .Checkmark
cell.cellLabel.textColor = UIColor.grayColor()
cell.cellLabel.font = UIFont.systemFontOfSize(20)
self.tableView.rowHeight = 50
moveToPL.hidden = false
} else {
cell.accessoryType = .None
cell.cellLabel.textColor = UIColor.blackColor()
cell.cellLabel.font = UIFont.systemFontOfSize(25)
self.tableView.rowHeight = 60
moveToPL.hidden = true
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let items = frc.objectAtIndexPath(indexPath) as! List
if (items.slcross == true) {
items.slcross = false
} else {
items.slcross = true
}
tableView.reloadData()
}
Is this my issue or is something else causing this?
Edit:
I tried changing my function in charge of moving items from this:
#IBAction func moveToPantry(sender: AnyObject) {
let sectionInfo = self.frc.sections![1]
let objectsToAppend = sectionInfo.objects as! [List]
for item in objectsToAppend {
item.slist = true
item.slcross = false
item.plist = false
item.slitem = item.pitem
item.slqty = item.pqty
item.sldesc = item.pdesc
item.slprice = item.pprice
item.slminqty = item.pminstepperlabel
}
}
to:
#IBAction func moveToSL(sender: AnyObject) {
if (frc.sections!.count > 0) {
let sectionInfo = self.frc.sections![1]
if (sectionInfo.name == "0") {
let objectsToAppend = sectionInfo.objects as! [List]
for item in objectsToAppend {
item.slist = true
item.slcross = false
item.plist = false
item.slitem = item.pitem
item.slqty = item.pqty
item.sldesc = item.pdesc
item.slprice = item.pprice
item.slminqty = item.pminstepperlabel
}
}
}
}
It is still throwing the error. It will move all the objects as long as section 0 isn't empty. Any more help in figuring this out would be appreciated! Thanks in advance.

tableView jumping scrolling after reloadData

My tableView scrolling is jumping when I reload tableView with new data. Here is the code for cellForRowAtIndexPath:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let section = indexPath.section
let index = indexPath.row
let info = data[sections[section]]![index] as ConversationMessage
if info.from == .Me {
var cell: ConversationDialogMeTableCell = tableView.dequeueReusableCellWithIdentifier("meCell", forIndexPath: indexPath) as! ConversationDialogMeTableCell
cell.backgroundColor = UIColor.clearColor()
cell.selectionStyle = .None
cell.messageLabel.text = info.text
return cell
} else if info.from == .Other {
var cell: ConversationDialogOtherTableCell = tableView.dequeueReusableCellWithIdentifier("otherCell", forIndexPath: indexPath) as! ConversationDialogOtherTableCell
cell.backgroundColor = UIColor.clearColor()
cell.selectionStyle = .None
cell.personName.textColor = UIColor(hex: 0x6d6d6d)
cell.messageContainerView.backgroundColor = UIColor(hex: 0x6d6d6d)
cell.messageContainerView.layer.cornerRadius = 5
cell.messageContainerView.clipsToBounds = true
Alamofire.request(.GET, info.personImage).response {
(request, response, data, error) in
let image = UIImage(data: data!, scale: 1)!
cell.personImage.image = image
cell.personImage.contentMode = UIViewContentMode.ScaleAspectFill
cell.personImage.layer.cornerRadius = cell.personImage.frame.height / 2
cell.personImage.clipsToBounds = true
}
cell.personName.text = info.personName
cell.personMessage.text = info.text
return cell
}
return UITableViewCell()
}
For the first load scrolling is smooth, but if I will add new data in my tableView and call reloadData() the scrolling is jumping when new cells are shown.
Here is the code where I insert new data to my model:
func client(client: PubNub!, didReceiveMessage message: PNMessageResult!) {
if message.data.subscribedChannel == self.channel {
if let messageInfo: AnyObject = message.data.message {
let date = (messageInfo["date"] as! String).getDateString()
let messageText = messageInfo["message"] as! String
let from: ConversationMessage.sendFromType = (messageInfo["userID"] as! String) == self.userID ? .Me : .Other
let image = messageInfo["userPhoto"] as! String
let name = messageInfo["userName"] as! String
if data[date] != nil {
data[date]!.append(ConversationMessage(text: messageText, from: from, personImage: image, personName: name, date: messageInfo["date"] as! String))
} else {
data[date] = [ConversationMessage(text: messageText, from: from, personImage: image, personName: name, date: messageInfo["date"] as! String)]
}
for section in self.sections {
self.data[section]! = sorted(self.data[section]!) { Utils.compareDateTime($0.date, with: $1.date, order: .OrderedAscending) }
}
tableView.reloadData()
tableViewScrollToBottom(false)
}
}
}
Maybe it happens because of function to scroll tableView to bottom:
func tableViewScrollToBottom(animated: Bool) {
let delay = 0.1 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue(), {
let numberOfSections = self.tableView.numberOfSections()
let numberOfRows = self.tableView.numberOfRowsInSection(numberOfSections - 1)
if numberOfRows > 0 {
let indexPath = NSIndexPath(forRow: numberOfRows - 1, inSection: (numberOfSections - 1))
self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: animated)
}
})
}
One more thing. Should I cache uploaded images? Maybe this is causing jumping scroll. Can someone help me to solve my issue?
Do not return UITableViewAutomaticDimension from
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath;
There may be two possible solutions -
Either you should return max height for your cell.
OR you may cache the cell.bounds.size.height from
tableView:willDisplayCell:forRowAtIndexPath: and return same value in estimatedHeightForRowAtIndexPath

Resources