Changing image properties UITableView Swift - ios

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("NewsCell", forIndexPath: indexPath) as! UITableViewCell
cell.imageView?.image = nil
let imgURL = NSURL(string: urlString)
cell.imageView?.image = UIImage(named: "first")
// cell.imageView?.image?.drawInRect(CGRectMake(0,0,50,50))
// or
// cell.imageView?.frame = CGRectMake(0,0,50,50)
// also tried this
cell.imageView?.image = UIImage(named: "first")
cell.imageView?.contentMode = .ScaleAspectFill
cell.imageView?.clipsToBounds = true
Neither seems to make a difference.
When the image loads from the URL online it takes its original size.
I have omitted the code used for asynchronous image downloading because I figure its the same problem here. If not let me know. Thanks !

You should set Mode property of your UIImageView into Aspect Fit where you are showing the image at your cell.

You need to set the contentmode of the imageView either in code or in Interface Builder, and then once you do that you need to usecell.imageView?.clipsToBounds = true

Related

IOS Swift how can hide the space of an Image inside a TableView

I have a tableView that contains a UIImageView and if the Image has a URL then the image displays and if not then no Image is displayed. The issue I have is that if there is no Image then a big blank spot occurs in the TableView as if there was an image. Is there a way to reduce the blank spot or hide it (Images below) ? The image is the big UIImageView in the center . This is my code when it comes to the Images
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyFeed", for: indexPath) as! MyFeed
if stream_image_string[indexPath.row].characters.count > 2 {
let strCellImageURL = self.stream_image_string[indexPath.row]
let imgURL: NSURL = NSURL(string: strCellImageURL)!
let request:NSURLRequest = NSURLRequest(url: imgURL as URL)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
DispatchQueue.main.async(execute: { () -> Void in
cell.post_image.image = UIImage(data: data!)
})
});
task.resume()
} else {
cell.post_image!.isHidden = true
cell.post_image!.image = nil
}
return cell
}
Essentially if the String coming back has 2 or more characters then it's a valid URL and the image is downloaded; the part that I am focused on is the else statement and this code
else {
cell.post_image!.isHidden = true
cell.post_image!.image = nil
}
So obviously if it goes in the else statement then there is no image and I set the Image to null or nil then I try to hide the extra white space by setting the Image to hidden however that does not work . Any idea on how I can hide the white space ? I have also been reading this question but it does not work iOS swift imageView cannot be hidden in TableViewCell
Give outlet of image's width and if there is no image then set constant of that outlet to "0".
e.g.
if(!image)
{
widthOfImage.constant = 0
}
I experienced the same problem myself. You need to create 2 cells for this. Like this:
override func tableView (_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (stream_image_string[indexPath.row] == "")
{
let cell = tableView.dequeueReusableCell (withIdentifier: "noImageMyFeed", for: indexPath) as! noImageMyFeed
return cell
}
else
{
let cell = tableView.dequeueReusableCell (withIdentifier: "MyFeed", for: indexPath) as! MyFeed
return cell
}
}
this video will help you in detail : https://www.youtube.com/watch?v=FAxtWtqeMIM
adapt the video to its own content, create a cell from scratch by simply deleting the image part

Resize table cell after image downloaded

I am using SDWebImage library to download image and load into image view inside a table cell.
I want to resize the table cell after the image is downloaded. Please advice. Many thanks.
Cell is not resize correctly after image set into image view
Cell resize correctly after dequeue and load again
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(GagListTableViewCell.cellId, forIndexPath: indexPath) as! GagListTableViewCell
cell.layoutMargins = UIEdgeInsetsZero
let gagDataCommand = gagDataSource[indexPath.row]
if let caption = gagDataCommand.caption {
cell.captionLabel.text = caption
}
if let imageUrlStr = gagDataCommand.images?.normal {
if let imageUrl = NSURL(string: imageUrlStr) {
cell.gagImage.sd_setImageWithURL(imageUrl, placeholderImage: UIImage(named: AppConstants.imagePlaceHolderName), completed: { (image, error, cacheType, url) in
//guess I need to redraw the layout here
})
} else {
//fail to get image url, set placeholder image to the cell instead
cell.gagImage.image = UIImage(named: AppConstants.imagePlaceHolderName)
}
}
return cell
}
You could use automatic dimension for tableview cell.
tableView.rowHeight = UITableViewAutomaticDimension

Can't get corner radius to work

Hi Im programming an chat app and i wan't the profile pictures to have a corner radius. This is my code. Btw Im using Parse as backend.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
var imageView = PFImageView()
let user = self.users[indexPath.row]
imageView.layer.cornerRadius = imageView.frame.size.width / 2
imageView.layer.masksToBounds = true
imageView.file = user[PF_USER_PICTURE] as? PFFile
cell.textLabel?.text = user[PF_USER_FULLNAME] as? String
cell.textLabel?.font = UIFont.boldSystemFontOfSize(24)
cell.imageView?.image = imageView.image
return cell
}
UPDATE:
The problem was that my cell.imageview did not have a frame.
Thanks for the answer Max K!
var imageView = PFImageView()
is a different image view than:
cell.imageView?.image = imageView.image
What shows on screen is the image view of your cell not this instance of PFImageView. If you want to have PFImageView in as a class of your's cell's image view you need to set that, either in the storyboard or by subclassing your cell.
You applied cornerRadius to layer of imageView created here:
var imageView = PFImageView()
But then you are using only its image property and assigning it to cell`s imageView:
cell.imageView?.image = imageView.image
Apply cornerRadius to cell's imageView.
You are setting cornerRadius on imageView that is not added to the screen later.
You have to set it on cell.imageView
if let imageView = cell.imageView {
imageView.layer.cornerRadius = imageView.frame.size.width / 2
}
You are adding corner to the imageView in
var imageView = PFImageView()
Instead add corner to the cell.imageView. It seems like you are using PFImageView to download image from a file. So you can modify the code like
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
var imageView = PFImageView()
let user = self.users[indexPath.row]
cell.imageView.layer.cornerRadius = imageView.frame.size.width / 2
cell.imageView.layer.masksToBounds = true
imageView.file = user[PF_USER_PICTURE] as? PFFile
cell.textLabel?.text = user[PF_USER_FULLNAME] as? String
cell.textLabel?.font = UIFont.boldSystemFontOfSize(24)
cell.imageView?.image = imageView.image
return cell
}
Or else make imageView of cell.imageView as PFImageView

Swift - UITableView lags with images

My problem is when I scroll down my UITableView, it looks too laggy. The images grab from facebook.
My code
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UserCell", forIndexPath: indexPath) as UITableViewCell
let user = users[indexPath.row] as User //2
if let nameLabel = cell.viewWithTag(100) as? UILabel { //3
nameLabel.text = user.name
}
if let dateCreatedLabel = cell.viewWithTag(101) as? UILabel {
dateCreatedLabel.text = user.distance
}
if let profilePictureView = cell.viewWithTag(103) as? UIImageView {
if let url = NSURL(string: "https://graph.facebook.com/\(user.profilePhoto)/picture?type=large") {
if let data = NSData(contentsOfURL: url){
profilePictureView.contentMode = UIViewContentMode.ScaleAspectFit
profilePictureView.image = UIImage(data: data)
}
}
}
return cell
}
Please advice how to make it smooth.
OMG, never do like this not only in scrolling controls, but in general UI also:
data = NSData(contentsOfURL: url)
Thats why you table lags, and you lucky enougth with fast internet. If you connection will be slow, you app will hang, may be forever. ALWAYS do network asyncronously!
Also, when you make you network async, your tableView will still lag here:
UIImage(data: data)
And even here if you have many controls in your cell:
cell.viewWithTag(101)
So, use some library to download images, this is surprisingly not so easy task as it seems to be, you will not do it right yourself according to you experience (as I can see it).
Make separate class for you cell and use IB to connect outlets.
Try AFNetworking, it has category for UIImageView to download images.
I already found the answer. Use Haneke instead NSData.
import Haneke
/* .. */
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UserCell", forIndexPath: indexPath) as UITableViewCell
let user = users[indexPath.row] as User //2
if let nameLabel = cell.viewWithTag(100) as? UILabel { //3
nameLabel.text = user.name
}
if let dateCreatedLabel = cell.viewWithTag(101) as? UILabel {
dateCreatedLabel.text = user.distance
}
if let profilePictureView = cell.viewWithTag(103) as? UIImageView {
if let url = NSURL(string: "https://graph.facebook.com/\(user.profilePhoto)/picture?type=large") {
profilePictureView.contentMode = UIViewContentMode.ScaleAspectFit
profilePictureView.hnk_setImageFromURL(url!)
}
}
return cell
}

UITableViewCell Images Changing after Scrolling Up and Down but TextLabel Text Remain Same (iOS8, Swift)

I'm trying to create an RSS app for practice. So my tableView cell has both textLabel and image. My textLabel's text and image data come from a dictionary stored in Core Data. Some cells have images, and some don't. The initial load of tableView looks fine to me. But when I scroll down and up, cell's images seem to change. The cells' textLabel text doesn't change though.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
cell.textLabel!.text = object.valueForKey("title")!.description
var image: UIImage?
if let imageData = object.valueForKey("imageData") as? NSData {
image = UIImage(data: imageData)
let itemSize = CGSizeMake(80, 80)
UIGraphicsBeginImageContext(itemSize)
let imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height)
image?.drawInRect(imageRect)
cell.imageView?.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
}
If the initial tableView loads correctly, that means my Core Data stores my data's mapping correctly. But when scrolling down and up, configureCell is being called again since it needs to redraw the cell. cell.textLabel!.text = object.valueForKey("title")!.description is set correctly again, but not image here. Don't know why it behaves like this. Please give some pointer.
I had this same problem once and I think it has something to do with the reused cell not being in the default state so sometimes the image you set is being reused. To fix it, I just did an else condition on imageData and set the image to a default image if no image was found. I'm sure you could set it to nil here as well.
if let image = UIImage(contentsOfFile: imagePath) {
cell.imageView.image = image
} else {
// Default image or nil
cell.imageView.image = UIImage(named: "Calendar")
}
And I wouldn't suggest storing images as raw data in core data, as this can be very inefficient. Instead, download them to your documents directory and store a file name in core data.
What i did was remove the image from imageView and set image again. It works for me.
cell.imageView.image = nil
cell.imageView.image = UIImage(named:"Calendar")

Resources