Hide custom ViewTableCell Button for a specific cell - ios

I'm facing a problem with a UITableViewCell.
When I generate my tableCells, I check if a value is equal to something and if so, I hide a custom button I made in my prototype cell. The problem is, the button with the identifier I hide is hidden in every Cell and not the current one only...
I looked around but can't find something to do... Could you help ? Here's my code, look at the line if currentPost.valueForKey... == "noLink". Thanks !
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
var cell = tableView.dequeueReusableCellWithIdentifier("postCell", forIndexPath: indexPath) as! PostTableViewCell
var currentCell = indexPath
var currentPost = post[indexPath.row]
var currentUser = followedInfo[currentPost.valueForKey("userID") as! String]
cell.username.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
cell.userProfil.layer.cornerRadius = 0.5 * cell.userProfil.bounds.size.width
cell.username.setTitle(currentUser?.valueForKey("username") as? String, forState: UIControlState.Normal)
cell.postArtist.text = currentPost.valueForKey("artistName") as? String
cell.postDescription.text = currentPost.valueForKey("postDescription") as? String
cell.postTitle.text = currentPost.valueForKey("songName") as? String
cell.postTime.text = "7J"
cell.postDescription.sizeToFit()
if currentPost.valueForKey("itunesLink") as? String == "noLink" {
cell.postItunes.hidden = true;
}else{
cell.postItunes.addTarget(self, action: "getToStore:", forControlEvents: .TouchUpInside)
}
if currentPost.valueForKey("previewLink") as? String == "noPreview" {
cell.postPlay.alpha = 0;
}else{
cell.postPlay.addTarget(self, action: "getPreview:", forControlEvents: .TouchUpInside)
}
if currentPost.valueForKey("location") as? String == "noLocalisation" {
cell.postLocation.text = "Inconnu"
}else{
cell.postLocation.text = currentPost.valueForKey("location") as? String
}
if currentUser?.valueForKey("profilePicture")! != nil{
var pictureFile: AnyObject? = currentUser?.valueForKey("profilePicture")!
pictureFile!.getDataInBackgroundWithBlock({ (imageData, error) -> Void in
var theImage = UIImage(data: imageData!)
cell.userProfil.image = theImage
})
}
if currentPost.valueForKey("coverLink") as? String == "customImage" {
var profilPictureFile: AnyObject? = currentPost.valueForKey("postImage")
profilPictureFile!.getDataInBackgroundWithBlock { (imageData , imageError ) -> Void in
if imageError == nil{
let image = UIImage(data: imageData!)
cell.postPicture.image = image
}
}
}else{
if currentPost.valueForKey("coverLink") as? String == "noCover"{
var cover = UIImage(named: "noCover")
cell.postPicture.image = cover
}else{
var finalURL = NSURL(string: currentPost.valueForKey("coverLink") as! String)
let request: NSURLRequest = NSURLRequest(URL: finalURL!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if error == nil {
var image = UIImage(data: data)
cell.postPicture.image = image
}
else {
println("Error: \(error.localizedDescription)")
}
})
}
}
return cell;
}

You are not setting the bottom back to visible if you want it to show, because you are reusing the cell the last setup is part of the cell, so as soon as you set it to hidden to true it will still hidden until you set hidden back to false, the best way to use reusable cell is to always set all the options to what you want to be for that cell to avoid the setting to be as the old cell.
if currentPost.valueForKey("itunesLink") as? String == "noLink" {
cell.postItunes.hidden = true;
}else{
cell.postItunes.hidden = false;
cell.postItunes.addTarget(self, action: "getToStore:", forControlEvents: .TouchUpInside)
}

Related

Image in table view [duplicate]

This question already has an answer here:
Asynchronously load image in uitableviewcell
(1 answer)
Closed 5 years ago.
I have a problem with the image in table view cell
The images are downloaded form the Google Firebase and in every cell there is one of that
But when I scroll up or down the images change automatically the index
Here is my code, someone can help me? thanks a lot!
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if postsArray[indexPath.row].imageNoImage == true{
let cell = tableView.dequeueReusableCell(withIdentifier: "imageLook", for: indexPath) as! imageLookTableViewCell
cell.authorLabel.text = self.postsArray[indexPath.row].author
cell.likesCountLabel.text = "\(self.postsArray[indexPath.row].likes!)"
cell.postID = postsArray[indexPath.row].postId
cell.textViewPost.text = self.postsArray[indexPath.row].textPost
let url = URL(string: postsArray[indexPath.row].pathToImage as! String)
if url != nil {
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async {
if data != nil {
cell.imagePost.image = UIImage(data:data!)
}else{
}
}
}
}
for person in self.postsArray[indexPath.row].peopleWhoLike {
if person == FIRAuth.auth()!.currentUser!.uid {
cell.likesBtn.isHidden = false
break
}
}
return cell
}
Your question is not very descriptive/well written, but I think your problem is that you are not caching your images.
Try this:
let imageCache = NSCache()
let cell = tableView.dequeueReusableCell(withIdentifier: "imageLook", for: indexPath) as! imageLookTableViewCell
cell.authorLabel.text = self.postsArray[indexPath.row].author
cell.likesCountLabel.text = "\(self.postsArray[indexPath.row].likes!)"
cell.postID = postsArray[indexPath.row].postId
cell.textViewPost.text = self.postsArray[indexPath.row].textPost
let url = URL(string: postsArray[indexPath.row].pathToImage as! String)
if url != nil {
if let cachedImage = imageCache.objectForKey(url) as? UIImage {
cell.imagePost.image = cachedImage
return
}
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async {
if data != nil {
if let myImageName = UIImage(data:data!){
imageCache.setObject(myImageName, forKey: url)
}
cell.imagePost.image = UIImage(data:data!)
}else{
}
}
}
}
for person in self.postsArray[indexPath.row].peopleWhoLike {
if person == FIRAuth.auth()!.currentUser!.uid {
cell.likesBtn.isHidden = false
break
}
}
return cell
}

swift3 uitableView reload makes screen blink

I am using UITableview and it looks similar with the feed of Instagram. The issue I have
I have a like function in each tableviewCell
when tap like button, it needs to update the screen and the screen blinks
In tableview cellForRowAt function, I have a network call to check the like and its number.
Please let me know if there is a way to avoid this blink. Should I avoid network call in this function or is there any other way?
U can see some part of my code below:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! StoryReviewTableViewCell
let review = ReviewArray[indexPath.row]
// 프로필 이미지랑 닉네임 설정
if let user = review.creator {
let nickname = user.getProperty("nickname") as! String
cell.profileName.text = nickname
if let profileURL = user.getProperty("profileURL") {
if profileURL is NSNull {
cell.profileImage.image = #imageLiteral(resourceName: "user_profile")
} else {
let url = URL(string: profileURL as! String)
DispatchQueue.main.async {
cell.profileImage.kf.setImage(with: url, placeholder: #imageLiteral(resourceName: "imageLoadingHolder"), options: [.transition(.fade(0.2))], progressBlock: nil, completionHandler: nil)
}
}
}
} else {
// 삭제된 유저의 경우
cell.profileName.text = "탈퇴 유저"
cell.profileImage.image = #imageLiteral(resourceName: "user_profile")
}
// 장소 이름
if let store = ReviewArray[indexPath.row].store {
cell.storeName.text = "장소: \(String(describing: store.name!))"
} else {
cell.storeName.text = "가게 이름"
}
// 라이크버튼 설정 - 라이크 모양은 여기서 컨트롤, delegate에서 user 라이크 컨트롤
DispatchQueue.global(qos: .userInteractive).async {
let likeStore = Backendless.sharedInstance().data.of(ReviewLikes.ofClass())
let dataQuery = BackendlessDataQuery()
let objectID = review.objectId!
let userID = UserManager.currentUser()!.objectId!
// print("objectID & userID: \(objectID) & \(userID)")
// 여기서 by가 현재 유저의 objectId이어야 하고, to는 이 리뷰의 objectId이어야 한다
dataQuery.whereClause = "by = '\(userID)' AND to = '\(objectID)'"
DispatchQueue.main.async {
likeStore?.find(dataQuery, response: { (collection) in
let likes = collection?.data as! [ReviewLikes]
// 하트를 안 눌렀을 때
if likes.count == 0 {
DispatchQueue.main.async {
cell.likeButton.setImage(#imageLiteral(resourceName: "like_bw"), for: .normal)
}
} else {
DispatchQueue.main.async {
cell.likeButton.setImage(#imageLiteral(resourceName: "like_red"), for: .normal)
}
}
}, error: { (Fault) in
print("라이크 불러오기에서 에러: \(String(describing: Fault?.description))")
})
}
// 좋아요 개수 세기
let countQuery = BackendlessDataQuery()
// to가 story의 objectID와 일치하면 땡
countQuery.whereClause = "to = '\(objectID)'"
let queryOptions = QueryOptions()
queryOptions.pageSize = 1
countQuery.queryOptions = queryOptions
DispatchQueue.global(qos: .userInteractive).async {
let matchingLikes = likeStore?.find(countQuery)
let likeNumbers = matchingLikes?.totalObjects
DispatchQueue.main.async {
if likeNumbers == 0 {
cell.likeLabel.text = "라이크 없음 ㅠ"
} else {
cell.likeLabel.text = "\(String(describing: likeNumbers!))개의 좋아요"
}
}
}
}
// 리뷰 평점 배당
cell.ratingView.value = review.rating as! CGFloat
// 리뷰 바디
cell.reviewBody.text = review.text
// 코멘트 개수 받아오기
DispatchQueue.global(qos: .userInteractive).async {
// 댓글수 찾기
let tempStore = Backendless.sharedInstance().data.of(ReviewComment.ofClass())
let reviewId = review.objectId!
let dataQuery = BackendlessDataQuery()
// 이 리뷰에 달린 댓글 모두 몇 개인지 찾기
dataQuery.whereClause = "to = '\(reviewId)'"
DispatchQueue.main.async {
tempStore?.find(dataQuery, response: { (collection) in
let comments = collection?.data as! [ReviewComment]
cell.replyLabel.text = "댓글 \(comments.count)개"
}, error: { (Fault) in
print("서버에서 댓글 얻어오기 실패: \(String(describing: Fault?.description))")
})
}
}
cell.timeLabel.text = dateFormatter.string(from: review.created! as Date)
return cell
}
U can see the button action here
#IBAction func likeButtonClicked(_ sender: UIButton) {
likeButton.isUserInteractionEnabled = false
// delegate action
delegate?.actionTapped(tag: likeButton.tag)
// image change
if sender.image(for: .normal) == #imageLiteral(resourceName: "like_bw") {
UIView.transition(with: sender, duration: 0.2, options: .transitionCrossDissolve, animations: {
sender.setImage(#imageLiteral(resourceName: "like_red"), for: .normal)
}, completion: nil)
self.likeButton.isUserInteractionEnabled = true
} else {
UIView.transition(with: sender, duration: 0.2, options: .transitionCrossDissolve, animations: {
sender.setImage(#imageLiteral(resourceName: "like_bw"), for: .normal)
}, completion: nil)
self.likeButton.isUserInteractionEnabled = true
}
}
This is part of my delegate function which reload only for the row
func changeLike(_ row: Int, _ alreadyLike: Bool, completionHandler: #escaping (_ success:Bool) -> Void) {
let selectedReview = ReviewArray[row]
let reviewId = selectedReview.objectId
// 그냥 유저 객체로 비교는 안되고 objectId로 체크를 해야 함
let objectID = Backendless.sharedInstance().userService.currentUser.objectId
let dataStore = Backendless.sharedInstance().data.of(ReviewLikes.ofClass())
// 좋아요 - alreadyLike가 true이면
if !alreadyLike {
// 객체 생성
let like = ReviewLikes()
like.by = objectID! as String
like.to = reviewId
dataStore?.save(like, response: { (response) in
DispatchQueue.main.async {
let indexPath = IndexPath(row: row, section: 0)
self.tableView.reloadRows(at: [indexPath], with: .none)
}
}
let cell = self.tblView.cellForRow(at: IndexPath(row: index, section: 0)) as! UITableViewCell
cell.btnLike.setImage(UIImage(named: (isReviewed! ? IMG_LIKE : IMG_UNLIKE)), for: .normal)
Just update the cell, instead of reloading whole data in the tableview.
Try to call data on button click instead of cellForRowAtIndexpath and use that button which clicked instead of reload data
#IBAction func likeButtonClicked(_ sender: UIButton) {
let buttonPosition:CGPoint = sender.convert(CGPointZero, to:self.tableView)
let indexPath = self.tableView.indexPathForRow(at: buttonPosition)
let cell = tableView.cellForRow(at: indexPath) as! StoryReviewTableViewCell
DispatchQueue.main.async {
likeStore?.find(dataQuery, response: { (collection) in
let likes = collection?.data as! [ReviewLikes]
// 하트를 안 눌렀을 때
if likes.count == 0 {
DispatchQueue.main.async {
cell.likeButton.setImage(#imageLiteral(resourceName: "like_bw"), for: .normal)
}
} else {
DispatchQueue.main.async {
cell.likeButton.setImage(#imageLiteral(resourceName: "like_red"), for: .normal)
}
}
}, error: { (Fault) in
print("라이크 불러오기에서 에러: \(String(describing: Fault?.description))")
})
}

Trying to get new value from a component on custom table cell class

I have an app which have a table view
and iam using custom cell class in my table
and this is my custom table cell class :
class addCommentTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
postText.layer.borderWidth = 1
postText.layer.borderColor = UIColor.grayColor().CGColor
postText.layer.cornerRadius = 3
}
#IBOutlet weak var postText: UITextView!
#IBOutlet weak var postCommentButton: UIButton!
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
i need to click the button in the cell class and get the value from the textView
so i added this code to make that :
class singleNewViewController: UIViewController , UITableViewDataSource , UITableViewDelegate{
override func viewDidLoad() {
let indexPath = NSIndexPath(forRow: 1, inSection: 0)
let secondCellPostComment = mainTable.dequeueReusableCellWithIdentifier("addCommentCell" , forIndexPath: indexPath) as! addCommentTableViewCell
let postButton = secondCellPostComment.postCommentButton
postButton!.addTarget(self, action: "postUserComment", forControlEvents: .TouchUpInside)
}
func postUserComment()
{
let indexPath = NSIndexPath(forRow: 1, inSection: 0)
let secondCellPostComment = mainTable.dequeueReusableCellWithIdentifier("addCommentCell" , forIndexPath: indexPath) as! addCommentTableViewCell
var textFieldComment = secondCellPostComment.postText
let textF = textFieldComment.text!
let request = NSMutableURLRequest(URL: NSURL(string: "http://mydomain/comment")!)
request.HTTPMethod = "POST"
let postString = "user_id=\(addResourcesViewController.userLoggedID)&news_id=\(singleNewViewController.newID)&comment=\(textF.text!)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data , response , error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
dispatch_async(dispatch_get_main_queue(), {
self.mainTable.reloadData()
})
}
task.resume()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (indexPath.row == 0 )
{
let cell = mainTable.dequeueReusableCellWithIdentifier("singleTableDetails", forIndexPath: indexPath) as! singleNewTableViewCell
let readmorebutton = cell.readmore
let focusComment = cell.addcomments
readmorebutton.addTarget(self, action: "loadURLinBrowser", forControlEvents: UIControlEvents.TouchUpInside)
focusComment.addTarget(self, action: "focusToView", forControlEvents: UIControlEvents.TouchUpInside)
let remoteImageUrlString = "http://mydomian/"+singleNewViewController.image
let imageURL = NSURL(string: remoteImageUrlString)
let myBlock: SDWebImageCompletionBlock! = { (image:UIImage! , error : NSError! , cacheType: SDImageCacheType! , imageURL: NSURL! ) -> Void in
print("Image with urk \(imageURL.absoluteString) is loaded" )
}
cell.cellImage.sd_setImageWithURL(imageURL, placeholderImage: UIImage(named:"welcome_bg") , options: SDWebImageOptions.ProgressiveDownload, completed: myBlock)
return cell
}else if (indexPath.row == 1 )
{
let cell = mainTable.dequeueReusableCellWithIdentifier("addCommentCell", forIndexPath: indexPath) as! addCommentTableViewCell
return cell
}
else
{
let cell = mainTable.dequeueReusableCellWithIdentifier("allCommentsCell", forIndexPath: indexPath) as! commentsTableViewCell
cell.commentUser.text = self.commentsUser[(indexPath.row - 2)]
cell.comment.text = self.comments[(indexPath.row - 2)]
return cell
}
}
}
the code is working but i don't get the value of the UITextView
and i tried to add a default value to the UITextView from the storyboard it's working but when i run in simulator and replace it with any string it's send the default value to the url any suggestion why it's not read any new values ?

Swift Cells Not Displaying

I have a profile page that is made up of two custom tableview cells. The first custom cell is the user's info. The second custom cell is the user's friend. The first row is the user's info, and all of the cells after that are the user's friends. My code worked in Xcode 6, but stopped working after the update.
Problem: A user with 2 friends, their profile page should have a table with three cells: 1 user info cell, 2 friend cells. However, the first and second cell aren't showing. Only the third cell is showing.
Clarification: There should be three cells. Cell 1 is not showing. Cell 2 is not showing. But Cell 3 is showing. Cell 1 is the user's info. Cell 2 is one friend. Cell 3 is another friend.
Here's my code:
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return friendList.count + 1
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0{
return 182.0
}else{
return 95.0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row != 0{
let cell = tableView.dequeueReusableCellWithIdentifier("friendCell", forIndexPath: indexPath) as! ProfileFriendTableViewCell
let friend = friendList[indexPath.row - 1]
cell.nameLabel.text = friend[1]
cell.usernameLabel.text = friend[2]
cell.schoolLabel.text = friend[3]
cell.sendRequestButton.tag = indexPath.row
var profileImageExists = false
if profileImages != nil{
for profileImage in profileImages{
if profileImage.forUser == friend[2]{
profileImageExists = true
cell.friendImageProgress.hidden = true
cell.profilePic.image = UIImage(data: profileImage.image)
UIView.animateWithDuration(0.2, animations: {
cell.profilePic.alpha = 1
})
}
}
}else if loadingImages == true{
profileImageExists = true
cell.friendImageProgress.hidden = true
cell.profilePic.image = UIImage(named: "profileImagePlaceholder")
UIView.animateWithDuration(0.2, animations: {
cell.profilePic.alpha = 1
})
}
if profileImageExists == false{
if Reachability.isConnectedToNetwork() == true{
let query = PFUser.query()
query?.getObjectInBackgroundWithId(friend[0], block: { (object, error) -> Void in
if error == nil{
if let object = object as? PFUser{
let friendProfilePicture = object.objectForKey("profileImage") as? PFFile
friendProfilePicture?.getDataInBackgroundWithBlock({ (data, error) -> Void in
if data != nil{
let image = UIImage(data: data!)
cell.profilePic.image = image
if let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext {
let newProfileImage = NSEntityDescription.insertNewObjectForEntityForName("ProfileImageEntity", inManagedObjectContext: managedObjectContext) as! ProfileImage
newProfileImage.forUser = friend[2]
newProfileImage.image = UIImagePNGRepresentation(image!)
do{
try managedObjectContext.save()
}catch _{
print("insert error")
}
}
}else{
cell.friendImageProgress.hidden = true
cell.profilePic.image = UIImage(named: "profileImagePlaceholder")
}
}, progressBlock: { (progress: Int32) -> Void in
let percent = progress
let progressPercent = Float(percent) / 100
cell.friendImageProgress.progress = progressPercent
cell.friendImageProgress.hidden = true
})
}
}
})
}
else{
cell.friendImageProgress.hidden = true
cell.profilePic.image = UIImage(named: "profileImagePlaceholder")
}
}
return cell
}else{
let cell = tableView.dequeueReusableCellWithIdentifier("profileTopCell", forIndexPath: indexPath) as! ProfileTableViewCell
var profileImageExists = false
if profileImages != nil{
for profileImage in profileImages{
if profileImage.forUser == PFUser.currentUser()!.username!{
profileImageExists = true
cell.profilePic.image = UIImage(data: profileImage.image)
}
}
}else if loadingImages == true{
profileImageExists = true
cell.profilePic.image = UIImage(named: "profileImagePlaceholder")
}
if profileImageExists == false{
if Reachability.isConnectedToNetwork() == true{
let profilePicture = PFUser.currentUser()!.objectForKey("profileImage") as? PFFile
profilePicture?.getDataInBackgroundWithBlock({ (data, error) -> Void in
if data != nil{
let image = UIImage(data: data!)
cell.profilePic.image = image
if let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext {
let newProfileImage = NSEntityDescription.insertNewObjectForEntityForName("ProfileImageEntity", inManagedObjectContext: managedObjectContext) as! ProfileImage
newProfileImage.forUser = PFUser.currentUser()!.username!
newProfileImage.image = UIImagePNGRepresentation(image!)
do{
try managedObjectContext.save()
}catch _{
print("insert error")
}
}
}else{
cell.profilePic.image = UIImage(named: "profileImagePlaceholder")
}
})
}else{
cell.profilePic.image = UIImage(named: "profileImagePlaceholder")
}
}
cell.nameLabel.text = PFUser.currentUser()!.objectForKey("Name") as? String
cell.usernameLabel.text = PFUser.currentUser()!.objectForKey("username") as? String
let friendNumber = PFUser.currentUser()!.objectForKey("numberOfFriends") as? Int
if friendNumber != 1{
cell.numberOfFriendsLabel.text = "\(friendNumber!) Friends"
}else{
cell.numberOfFriendsLabel.text = "1 Friend"
}
return cell
}
}
Try to use estimatedRowHeightand rowHeight = UITableViewAutomaticDimension on your viewDidLoad or viewWillAppear and on heightForRowAtIndexPath return UITableViewAutomaticDimension, remember to put constraints on your custom cell, so these can work properly.
Thanks to Jeremy Andrews (https://stackoverflow.com/a/31908684/3783946), I found the solution:
"All you have to do is go to file inspector - uncheck size classes - there will be warnings etc.run and there is the data - strangely - go back to file inspector and check "use size classes" again, run and all data correctly reflected. Seems like in some cases the margin is set to negative."
It was just a bug.

Synching parse object array with UIImageView array

I'm building an app for creating events which uses parse as a back end. The main interface is a collection view with a custom cell, which when flipped displays an array of UIImageViews added to the cell file as an IBOutlet collection.
#IBOutlet var imageViewArray: [UIImageView]!
Inside the event.getDataInBackground block I have this code, which doesn't get called for some reason, I think it will work once it is but does anyone know what's up? Thanks!
//gets profile pictures for image view array on back of cell
if let attendeeArray = event?.objectForKey("attendees") as? [PFUser] {
for var index = 0; index < attendeeArray.count; ++index {
let profileImageView = cell.imageViewArray[index]
let usr : PFUser = (attendeeArray[index] as PFUser?)!
if let picture = usr.objectForKey("profilePicture") as? PFFile {
picture.getDataInBackgroundWithBlock({ (data, error) -> Void in
profileImageView.image = UIImage(data: data!)
})
}
}
}
The whole cell for row at index path method (The creator image shows up and is called but the attendee array part is not).
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
//sets up cell
let cell : EventCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! EventCell
//adds attend action
cell.attendButton.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
//queries parse for events
let event = events?[indexPath.row]
event?.eventImage.getDataInBackgroundWithBlock({ (data, error) -> Void in
if let data = data, image = UIImage(data: data) {
cell.eventBackgroundImage.image = image
cell.eventTitleLabel.text = event?.eventTitle
//gets profile picture of events creator
if let eventCreator = event?.objectForKey("user") as? PFUser {
if let creatorImage = eventCreator.objectForKey("profilePicture") as? PFFile {
creatorImage.getDataInBackgroundWithBlock({ (data, error) -> Void in
cell.creatorImageView.image = UIImage(data: data!)
})
}
}
//gets profile pictures for image view array on back of cell
if let attendeeArray = event?.objectForKey("attendees") as? [PFUser] {
for var index = 0; index < attendeeArray.count; ++index {
let profileImageView = cell.imageViewArray[index]
let usr : PFUser = (attendeeArray[index] as PFUser?)!
if let picture = usr.objectForKey("profilePicture") as? PFFile {
picture.getDataInBackgroundWithBlock({ (data, error) -> Void in
profileImageView.image = UIImage(data: data!)
})
}
}
}
//sets correct category for cell image
if event?.category == "" {
cell.categoryImageView.image = nil
}
if event?.category == "The Arts" {
cell.categoryImageView.image = UIImage(named: "Comedy")
}
if event?.category == "The Outdoors" {
cell.categoryImageView.image = UIImage(named: "Landscape")
}
if event?.category == "Other" {
cell.categoryImageView.image = UIImage(named: "Dice")
}
if event?.category == "Sports" {
cell.categoryImageView.image = UIImage(named: "Exercise")
}
if event?.category == "Academics" {
cell.categoryImageView.image = UIImage(named: "University")
}
if event?.category == "Science" {
cell.categoryImageView.image = UIImage(named: "Physics")
}
if event?.category == "Entertainment" {
cell.categoryImageView.image = UIImage(named: "Bowling")
}
if event?.category == "Food & Drinks" {
cell.categoryImageView.image = UIImage(named: "Food")
}
if let date = event?.eventDate {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
cell.eventDescriptionLabel.text = event?.eventDescription
cell.eventDateLabel.text = dateFormatter.stringFromDate(date)
}
}
})
cell.layer.cornerRadius = 20
return cell
}
EDITED:
//gets profile pictures for image view array on back of cell
if let attendeeArray = event?.objectForKey("attendees") as? [PFUser] {
for var index = 0; index < attendeeArray.count; ++index {
let profileImageView = cell.imageViewArray[index]
let usr : PFUser = (attendeeArray[index] as PFUser?)!
usr.fetchIfNeededInBackgroundWithBlock({ (object: PFObject?, error: NSError?) -> Void in
if let picture = object!.objectForKey("profilePicture") as? PFFile {
picture.getDataInBackgroundWithBlock({ (data, error) -> Void in
profileImageView.image = UIImage(data: data!)
})
}
})
}
}
You need to fetch the usr before you can get picture
usr.fetchIfNeededInBackgroundWithBlock({ (object: PFObject?, error: NSError?) -> Void in
if let picture = object.objectForKey("profilePicture") as? PFFile {
picture.getDataInBackgroundWithBlock({ (data, error) -> Void in
profileImageView.image = UIImage(data: data!)
})
}
})

Resources