UIButton inside UITableViewCell facing image changing issue while tableview get scrolled - uitableview

I am doing "Add to favourite Page" using SWIFT. In my product list table, "Wish" button is there. That button is dragged from Storyboard. If User clicks the button, that image change to another new one. I did upto this part, exactly working too. But, if we scroll the tableview, automatically another cell button image has been changed to new one. I don't know how and why? How to solve this? Kindly guide me.
//MY CODING IS BELOW
unc tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell1 = product_tableview.dequeueReusableCellWithIdentifier("productmain", forIndexPath: indexPath) as product_tblCell
image_url = arrayFromJson[indexPath.row].valueForKey("image_url") as NSString
let imgurl = NSURL(string: image_url)!
var imgdata : NSData = NSData(contentsOfURL: imgurl)!
prod_img = UIImage(data: imgdata)!
id = String(arrayFromJson[indexPath.row].valueForKey("id") as NSInteger)
code = arrayFromJson[indexPath.row].valueForKey("code") as NSString
descrip = arrayFromJson[indexPath.row].valueForKey("description") as NSString
name = arrayFromJson[indexPath.row].valueForKey("name") as NSString
price = String(arrayFromJson[indexPath.row].valueForKey("price") as NSInteger)
cell1.name.text = name
cell1.prod_desc.text = descrip
cell1.prod_price.text = price
cell1.prod_image.image = prod_img
cell1.wish_image_but.addTarget(self, action : Selector("to_wish_list:"), forControlEvents: UIControlEvents.TouchUpInside)
return cell1
}
func to_wish_list(sender : UIButton)
{
var img = UIImage(named: "wish_2.png")
sender.setImage(img, forState: UIControlState.Normal)
sender.enabled = false
}

The reason is when you scroll the tableview and your cell goes beyond visible boundry, it is used for displaying another data. And when it has comes back is visible boundry it's data is set again.
That means, you have to check if the cell has been marked for "to_wish_list" while setting cell data. if yes then set the UIImage(named: "wish_2.png") by default else set defult image.

Related

Adding a UIButton to an array

I am relatively new to coding in Swift and I'm updating an app that is currently in the app store. I am currently creating an array for contents in a cell for a tableView that I made in a xib file. Here is what it looks like:
`struct callData {
let cell : Int?
let hotlineName : String?
let phoneNumber : String?
let callBtn : UIButton?
let iconImg : UIImage?
init(cell:Int,hotlineName:String,phoneNumber:String, callBtn:UIButton, iconImg:UIImage) {
self.cell = cell
self.hotlineName = hotlineName
self.phoneNumber = phoneNumber
self.callBtn = callBtn
self.iconImg = iconImg
}
}
class _ViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var arrayOfCallData = [callData(
cell: 0,
hotlineName:"",
phoneNumber:"",
callBtn:"",
iconImg: #imageLiteral(resourceName: "smartphone")
)]
`
I'm not sure how to insert a button (callBtn) into an array (arrayOfCallData) without it providing plenty of errors. The purpose of it is to call the number from within the string from the app but I'm not sure how to implement an action for the button to call.
here is an example of the code for calling from within the app:
let url = NSURL(string: "tel://8004424673")!
UIApplication.shared.open(url as URL)
I want to be able to incorporate this into the array (callBtn) so that I can create multiple buttons that can call different numbers.
In your callData, save your phone number as callBtnAction and you can fetch it back in selector method.
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cellIdendifier: String = "CallDataCell"
let cellData = arrayOfCallData[indexPath.row]
let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdendifier, for: indexPath)
let button = UIButton.init()
button.frame = CGRect.zero //Set your frame here
button.setTitle(cellData.callBtnText, for: UIControlState.normal)
button.tag = indexPath.row
button.addTarget(self, action: Selector(("buttonClicked:")), for: UIControlEvents.touchUpInside)
cell.addSubview(button)
return cell
}
func buttonClicked(sender:UIButton) {
let selectedRow = sender.tag
let callData = arrayOfCallData[selectedRow]
let action = callData.callBtnAction
print(action)
}
The cells should own the views (e.g. buttons) and your data should be used to decorate those views. So if you remove the UI concerns from your data e.g. replacing the UIButton reference with a button title string, you can apply that data to the cell views in the cellForRowAt method.

How to manage shopping cart in UITableView with dequeueReusableCellWithIdentifier in swift?

My self.totalPriceLabel show's total price of all shop Product.It works fine but when is i scroll the cell the go off screen due to dequeueReusableCellWithIdentifier self.totalPriceLabel gets incorrect value.i am saving value in array which is stored in NSUserDefaults.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell : CartCell? = tableView.dequeueReusableCellWithIdentifier("cartCell") as! CartCell!
if(cell == nil)
{
cell = CartCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cartCell")
}
cell?.itemCount.layer.cornerRadius = 5
cell?.clipsToBounds = true
cell?.itemCount.layer.borderWidth = 1
cell?.itemCount.layer.borderColor = UIColor.blackColor().CGColor
cell?.itemMinus.tag = indexPath.row
cell?.itemPlus.tag = indexPath.row
cell?.itemDelete.tag = indexPath.row
let key = self.readArray[indexPath.row]
cell?.itemCount.text = String("\(key.allValues[0])")
let tupleVar = getProductNameFromCharacter(String("\(key.allKeys[0])"))
cell?.itemName.text = tupleVar.tempName
cell?.itemPrice.text = String("\(tupleVar.price)")
//Actual Logic
let tempCount = key.allValues[0] as! Double
let nextItemPrice = (cell!.itemPrice.text! as NSString).doubleValue * tempCount
self.totalPriceLabel.text = String("\((self.totalPriceLabel.text! as NSString).doubleValue + nextItemPrice)")
return cell!
}
Issue: As scroll cell getting wrong values.for self.totalPriceLabel.
self.totalPriceLabel.text = String("((self.totalPriceLabel.text! as
NSString).doubleValue + nextItemPrice)")
How to get cell value which just goes out off screen ? how to fix this issue due to scrolling?
cellForRowAtIndexpath is the wrong place to do that calculation. You are assuming that iOS will call this function once for each cell. This isn't the case. This function is called to display a single cell. It could very well get called multiple times for the same cell as you scroll up and down.
You should be updating that total when you add or remove items from the underlying data (self.readArray).
Also, add code to change the total when the quantity button is tapped.
If you want more specific help, post the entire controller.

Prototype cells are shaking or shivering when scrolling the table view in swift

I am new to swift I have an issue that is when scrolling cells in table view cells are shaking or shivering when scrolling the table view .I follow the below code can any one tell me the reason .I tested in IOS simulator not in real time device .my question is why it is shaking in simulator
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("transportCell") as! UITableViewCell
cell.textLabel?.text = transportItems[indexPath.row]
var imageName = UIImage(named: transportItems[indexPath.row])
cell.imageView?.image = imageName
return cell
}
I suggest you to perform the following changes:
instead of the lines:
var imageName = UIImage(named: transportItems[indexPath.row])
cell.imageView?.image = imageName
use the lines:
let qos = Int(QOS_CLASS_USER_INITIATED.rawValue)
dispatch_async(dispatch_get_global_queue(qos, 0)) { () -> Void in
if let imageName = UIImage(named: transportItems[indexPath.row])) {
dispatch_async(dispatch_get_main_queue()) {
self.cell.imageView?.image = imageName
}
}
}

Button in cell is being added when it is not supposed to be

So I have a settings button and it is only supposed to be added to the cell with the current users name. However, it seems to being randomly added to a cell. In the statement in which I create the button it is only being created once however it is being added to multiple cells. I have attached images of the problem and ps the current username is "test", so the settings button should not be in the same cell as the matt short user. Thanks and below is the attached code of the function in which i am creating and adding the button subview.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell : UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("chatCell") as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "chatCell")
}
cell!.selectionStyle = UITableViewCellSelectionStyle.None
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
var sectionTitle = self.friendSectionTitles[indexPath.section]
var friendArray: [String]! = friendDict[sectionTitle]
var friend = friendArray[indexPath.row]
if sectionTitle == "me" && friend == PFUser.currentUser().username {
var settingsButton: UIButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
settingsButton.frame = CGRectMake(screenWidth - 100 , 5, 50, 30)
settingsButton.addTarget(self, action: "settingsButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
settingsButton.setTitle("Settings", forState: UIControlState.Normal)
cell!.addSubview(settingsButton)
}
cell!.textLabel!.text = friend
return cell!
}
In the statement in which I create the button it is only being created once however it is being added to multiple cells
Because cells, once created, are reused for other rows of the table. If you don't want the button to appear in a reused cell, you will need (in your implementation of cellForRowAtIndexPath:) to detect its presence and remove it (or at least hide it) for every row that is not supposed to have it.

How to display Different Images for different Index in TableView?

I am developing a simple table app where I want to display Image in every cell and I have done this and one Image is displayed In all cells :
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
// Create the cell
var cell : UITableViewCell = self.TableViewData.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
cell.textLabel?.text = self.iteams[indexPath.row]
cell.imageView?.image = UIImage(named: "creme_brelee.jpg")
return cell
}
It works fine but I want to display more Images for different cell and for that I have taken on array:
var thumbils : [String] = ["egg_benedict.jpg", "mushroom_risotto.jpg", "full_breakfast.jpg", "hamburger.jpg", "ham_and_egg_sandwich.jpg", "creme_brelee.jpg", "white_chocolate_donut.jpg", "starbucks_coffee.jpg", "vegetable_curry.jpg", "instant_noodle_with_egg.jpg", "noodle_with_bbq_pork.jpg", "japanese_noodle_with_pork.jpg", "green_tea.jpg", "thai_shrimp_cake.jpg", "angry_birds_cake.jpg", "ham_and_cheese_panini.jpg"]
but now I dont know how to display different image for different index in tableView.
I know In objective-C we can do like this:
cell.imageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];
But I don't know how to do this in swift.
Please help me for this.
You can use below code to fetch an image from array:
cell.imageView?.image = UIImage(named: thumbils[indexPath.row])
use below code
cell.imageView?.image = UIImage(self.iteams(indexPath.row)
var imagesArray = [UIImage]()
imagesArray.append(UIImage(named: "mypic.png")!)
cell.imageView?.image = imagesArray[indexPath.row]
return cell

Resources