I need to Update an label by clicking on an Button in the same cell. Why does my code doesn't work ?
#IBAction func actionFaveUnfave(sender: AnyObject) {
let cell = self.tableView.cellForRowAtIndexPath(sender.indexPath)
println(cell?.labelFavedTimes)
cell.labelFavedTimes = "22"}
cell?.labelFavedTimes.text = "22"
BTW
self.tableView.cellForRowAtIndexPath(sender.indexPath)
can return nil if cell is not visible
I solved the problem by using superview...here is my solution:
let button = sender as! UIButton
let view = button.superview!
let cell = view.superview as! TableViewCellHome
let indexPath = tableView.indexPathForCell(cell)
println(indexPath)
if(indexPath != nil){
var cell = self.tableView.cellForRowAtIndexPath(indexPath!) as! TableViewCellHome
cell.labelFavedTimes.text = favedTimesInt + " Faves"
}
cell.labelFavedTimes.text = "22"
Related
I have a chat app with 2 custom cells, sender and receiver cell. Once the cells are populated, only the ones with "show image" text can be clicked. I am trying to click on these cells so that
i can hide the label
I can show the image from the url
The tap function works but i am not able to do the above steps. Kindly help because i do not know how to go about this
Here is my code
#objc
func tapFunctionCell(sender:UITapGestureRecognizer) {
print("tap again sen")
let tapLocation = sender.location(in: tblViewChat)
let indexPath = self.tblViewChat.indexPathForRow(at: tapLocation)
let position = indexPath?.row ?? 0
print(position)
let cell = tblViewChat.dequeueReusableCell(withIdentifier: "senderCell") as! SenderTblCell
cell.lblMessage.isHidden = true
let url = URL(string:objChatVM.getMessage(index:position))
print(url)
cell.ImageB.kf.setImage(with:url)
cell.ImageB.isHidden = false
}
#objc
func tapFunction(sender:UITapGestureRecognizer) {
print("tap again receive")
let cell2 = tblViewChat.dequeueReusableCell(withIdentifier: "receiverCell") as! ReceiverTblCell
cell2.lblMessage.isHidden = false
let tapLocation = sender.location(in: tblViewChat)
let indexPath = self.tblViewChat.indexPathForRow(at: tapLocation)
let position = indexPath?.row ?? 0
print(position)
let url = URL(string:objChatVM.getMessage(index:position))
print(url)
cell2.imageButton.kf.setImage(with:url)
cell2.imageButton.isHidden = false
}
Issues in your tap function code. When you want to get a cell from the index path use the cellForRow method of table view. so instead of this
let cell = tblViewChat.dequeueReusableCell(withIdentifier: "senderCell") as! SenderTblCell
use this for both tap action.
let cell = tblViewChat.cellForRow(at: indexPath) as! SenderTblCell
Im trying to implement 3D touch support for my app and I'm encountering some issues at the moment
//3D Touch - Peek
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = tableView.indexPathForRow(at: location),
let cell = tableView.cellForRow(at: indexPath) as? CustomCell else {return nil}
let identifier = "TemplateTestViewController"
guard let BarVC = storyboard?.instantiateViewController(withIdentifier: identifier) as?
TemplateTestViewController else { return nil }
//Set Ups the Image Template :
BarVC.HeaderprofileImage?.image = UIImage(named: ProfileImages[indexPath.row] + "jpg")
//Sets Up Bar Or Club Text :
BarVC.BarOrClubLabel?.text = ProfileBarOrClub[MyIndex]
//Sets Up Age Text :
BarVC.AgeLabel.text = AgeText[MyIndex]
//Sets Up Phone Number Text :
BarVC.ProfilePhoneNumberLabel?.setTitle(ProfilePhoneNumbers[indexPath.row], for: .normal)
if #available(iOS 9.0, *) {
previewingContext.sourceRect = cell.frame
} else {
// Fallback on earlier versions
}
return BarVC
}
As you can see I'm trying to change the data between each cells with MyIndex which is basically indexPath.row. I don't get any errors and yet when i run the app the data isn't changed between different cells being peeked...
any help will be really appreciated !
I have to arrays which populates the values of searchController.
let textLabel = ["Uni", "Uni", "Faber-Castell", "Faber-Castell","Faber-Castell", "Pilot", "Pilot"]
let detailTextLabel = ["Pen", "Pencil", "Crayon", "Mechanical Pencil", "Contour Pencil", "Eraser", "Sharpener"]
These two arrays pair while reloading the data of UITableViewController. Like (Uni, Pen), (Uni, Pencil), (Faber-Castell, Crayon) ...
In pairs, first one is the cell title, second one is the subtitle. I followed iOSCreator's tutorial.
My problem is when I search text it only updates title section, not the subtitle as it was expected.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
// 3
if (self.resultSearchController.active) {
// it only updates textLabel. But when I add detailTextLabel
// subtitles comes wrong because first array contains one element
// more than twice.
cell.textLabel?.text = filteredTableData[indexPath.row]
return cell
} else {
cell.textLabel?.text = tableData[indexPath.row]
return cell
}
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
filteredTableData.removeAll(keepCapacity: false)
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %#", searchController.searchBar.text)
let array = (tableData as NSArray).filteredArrayUsingPredicate(searchPredicate)
filteredTableData = array as! [String]
self.tableView.reloadData()
}
Use the single array like this:
let penList = ["Uni:Pen", "Uni:Pencil", "Faber-Castell:Crayon"]
let result = filteredTableData[indexPath.row] // example: "Uni:Pen"
let clearResult = String(result.characters.map { $0 == ":" ? " " : $0 })
// clearResult like this "Uni Pen"
cell.textLabel?.text = clearResult
Also you can get data seperated
let result = filteredTableData[indexPath.row]
let resultArray = result.componentsSeparatedByString(":")
let firstText = resultArray[0] // title text
let secondText = resultArray[1] // subtitle text
I have a UICollectionView where i display cell that contain an png image each cell. When i display two er more cell beside each other the scroll will lag, but when i only display cells below eachother the scroll run more smotthly.
In my cellForItemAtIndexPath i got this 2 lines of coe which was recommended in another stackoverflow thread:
cell.layer.shouldRasterize = true;
cell.layer.rasterizationScale = UIScreen.mainScreen().scale
It did help a little, but not much.
The way i get the image is by making an extension to ImageView:
import Foundation
import Alamofire
let imageCache = NSCache()
extension UIImageView {
public func imageFromUrl(urlString: String) {
if let image = imageCache.objectForKey(urlString) as? UIImage {
self.image = nil
self.image = image
}
else {
self.image = nil
Alamofire.request(.GET, urlString).responseJSON{
response in
if let tilbudimage = UIImage(data: response.data!){
self.image = tilbudimage
imageCache.setObject(tilbudimage, forKey: urlString)
}
}
}
}
}
And in my cellForItemAtIndexPath i init the cell image like:
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("postcol", forIndexPath: indexPath) as! PostColViewCell
cell.PostImg.imageFromUrl(firstImage["imgurl"].string!)
Display cells this way lag when scroll:
Display cells this way does not lag when scroll
Here is my whole cellForItemAtIndexPath:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("postcol", forIndexPath: indexPath) as! PostColViewCell
cell.layer.shouldRasterize = true;
cell.layer.rasterizationScale = UIScreen.mainScreen().scale
cell.layer.cornerRadius = 10
let post = self.postArray[indexPath.row]
let firstImage = post["images"].array![0]
if(post["newpost"].int! <= 1)
{
cell.NewLabel.hidden = false
}
else
{
cell.NewLabel.hidden = true
}
cell.ProfilePicture.imageFromUrl(post["user"]["photourl"].string!)
cell.ProfilePicture.contentMode = .ScaleAspectFill
cell.ProfilePicture.clipsToBounds = true
cell.NameLabel.text = post["user"]["firstname"].string! + " " + post["user"]["lastname"].string!
cell.PriceLabel.text = String(post["price"].int!) + " kr."
cell.NameLabel?.userInteractionEnabled = true
cell.NameLabel?.tag = indexPath.row
let tapped:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "seeUser:")
tapped.numberOfTapsRequired = 1
cell.NameLabel?.addGestureRecognizer(tapped)
cell.TitleText.textColor = UIColor.blackColor()
cell.TitleText.labelSpacing = 5; // distance between start and end labels
cell.TitleText.pauseInterval = 2.0; // seconds of pause before scrolling starts again
cell.TitleText.scrollSpeed = 30; // pixels per second
cell.TitleText.textAlignment = NSTextAlignment.Left; //centers text when no auto-scrolling is applied
cell.TitleText.fadeLength = 12;// length of the left and right edge fade, 0 to disable
cell.TitleText.font = UIFont(name: (cell.TitleText?.font.fontName)!, size: 12)!
cell.TitleText.text = post["title"].string!
if(cell.PostImg.image != nil)
{
cell.PostImg.imageFromUrl(firstImage["imgurl"].string!)
}
cell.PostImg.contentMode = .ScaleAspectFill
cell.PostImg.clipsToBounds = true
//Comment label layout
cell.CommentLabel.text = String(post["comments"].array!.count)
cell.CommentLabel.textColor = UIColor.whiteColor()
// Here is the magic
cell.CommentLabel.icon = UIImage(named: "Comment")// Set icon image
cell.CommentLabel.icon = cell.CommentLabel.icon!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
cell.CommentLabel.tintColor = UIColor.whiteColor()
cell.CommentLabel.iconPadding = 5 // Set padding between icon and label
cell.CommentLabel.iconPosition = SMIconLabelPosition.Left // Icon position
cell.CommentLabel.textAlignment = .Right
//Distance label layout
if (post["distance"].double! < 1)
{
cell.DistanceLabel.text = LoginViewController.CurrentUser.CurrentLocation
}
else
{
let formatter = NSNumberFormatter()
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 0
cell.DistanceLabel.text = formatter.stringFromNumber(post["distance"].double!)! + " km"
}
cell.DistanceLabel.textColor = UIColor.whiteColor()
// Here is the magic
cell.DistanceLabel.icon = UIImage(named: "Location")// Set icon image
cell.DistanceLabel.icon = cell.DistanceLabel.icon!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
cell.DistanceLabel.tintColor = UIColor.whiteColor()
cell.DistanceLabel.iconPadding = 0 // Set padding between icon and label
cell.DistanceLabel.iconPosition = SMIconLabelPosition.Left // Icon position
cell.DistanceLabel.textAlignment = .Left
return cell
}
Having issues to assign uiImageFile = image!. If It try to assign self.myImage = image! where myImage is a global variable it works.
Is it something possible to be done?
The code is retrieving images ok, also the cell will take an image if pointed directly. Just this bridge that is not working. And it only do not work for the image.
Also the following test line println("TESTSTRING\(indexPath.row)") just above the return is being able to get and print value from testString = "\(indexPath.row)" that is inside getDataInBackgroundWithBlock.
Sorry about the question title. Not sure how to resume the issue in a single sentence.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! HobbieFeedTableViewCell
let object: PFObject = self.timelineData.objectAtIndex(indexPath.row) as! PFObject
var myText = object.objectForKey("postText") as? String
let userImageFile = object.objectForKey("postImage") as? PFFile
var uiImageFile = UIImage()
var testString = String()
println(userImageFile, indexPath.row)
if userImageFile != nil {
userImageFile?.getDataInBackgroundWithBlock({ (imageData:NSData?, error:NSError?) -> Void in
if error == nil {
if let myImageData = imageData {
let image = UIImage(data:myImageData)
self.myImage = image!
uiImageFile = image!
testString = "\(indexPath.row)"
}
}
}, progressBlock: { (percent: Int32) -> Void in
})
}
cell.cellTitle.text = myText
cell.cellImage.image = uiImageFile
// cell.cellImage.image = myImage
println("TESTSTRING\(indexPath.row)")
return cell
}
cell.cellImage.image = uiImageFile
gets executed before uiImageFile has been retrieved. This is because the
getDataInBackgroundWithBlock
returns right away before the retrieval is done.
You can fix it by: (1) Retrieve all images into a local array in the viewDidLoad function (2) Use push notification on completion on retrieval to trigger a tableview.reload