I am trying to display a rounded image for every custom cell in a table view. I am already changing its cornerRadius, but for some reason the image still will appear fully - even when the ImageView's borders are already set round.
Here's a piece of the code:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> CustomTableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "celda", for: indexPath) as! CustomTableViewCell
cell.imgView.layer.borderWidth = 1
cell.imgView.layer.borderColor = UIColor.black.cgColor
cell.imgView.layer.cornerRadius = cell.imgView.frame.height/2
//...the rest of function
//image is added to imgView eventually
}
And here is the result in the sim
I tried putting the code in override func awakeFromNib in the cell file but I had the same result.
Any advice is welcome :)
Please try this code by following step:
step1:
Make the height and width same of image view. Add the 1:1 ratio in storyboard in image view for equal height and width.
step2:
cell.imgView.layer.cornerRadius = cell.imgView.frame.height/2
cell.imgView.clipsToBounds = true
It may helps you.Thank you.
Related
I have a very similar question as posted here (Dynamic UIImageView Size Within UITableView) where I'm trying to dynamically retrieve an image from Firebase and make the resulting tableview adjust to the height of the image given a fixed width across the screen based on the aspect ratio. All the articles I read says to make the cell calculation based on cellforRowAt, but my actual image is within the TableViewCell. Can someone please help?
Tableview controller:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FeedTableViewCell", for: indexPath) as! FeedTableViewCell
cell.configureCell(post: postArray[indexPath.row])
return cell
}
TableViewCell:
func configureCell(post: Post){
self.postImage.sd_setImage(with: URL(string: post.postImageURL),
placeholderImage: UIImage(named: "default"))
}
you have cell.setNeedsLayout() inside the completion handler of setting image method, like this:
cell. postImage.kf.setImage(with: URL) { _, _, _, _ in
cell.layoutIfNeeded()
}
First of all, you need to use Autolayout to calculate the proper cell height by creating a proper set of constraints that would determine the cell height based on content. I am going to assume you did that.
Then you have to tell the tableView you want it to use Autolayout to calculate height:
// my best estimation of the height
tableView.estimatedRowHeight = 144
// but the real height is calculated by autolayout
tableView.rowHeight = UITableViewAutomaticDimension
Now this would work if the autolayout could calculate the height correctly in cellForRowAt. But since the image is downloaded asynchronously, the image is set later, when the cell may be already presented. This requires you to provide a way in which a cell can tell the tableView that it has downloaded its content and its layout needs to be recalculated. To do so, use this method in the viewController with the tableView:
func recalculateTableViewLayout() {
self.tableView.beginUpdates()
self.tableView.setNeedsLayout()
self.tableView.endUpdates()
}
You will need to pass the reference to the viewController with the tableView to each cell (I recommend to use delegate pattern for that, here for brevity I will simply sketch it using it directly):
class FeedTableViewCell: UITableViewCell {
weak var feedViewController: FeedViewController?
// etc.
And in the cellForRowAt:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FeedTableViewCell", for: indexPath) as! FeedTableViewCell
cell.feedViewController = self
cell.configureCell(post: postArray[indexPath.row])
return cell
}
Then use completion handler of sd_setImage to tell the tableView to recalculate its layout when the image gets downloaded:
func configureCell(post: Post){
self.postImage.sd_setImage(with: URL(string: post.postImageURL), placeholderImage: UIImage(named: "default")) { (image, error, cache, url) in
self.feedViewController?.recalculateTableViewLayout()
}
}
I have a tableview in where each cell has a label. The datasource of this label is from the firebase api. Now, initially the label is loaded in a perfect form. As you scroll through and if any label is of a shorter text width, the rest of the cell, alter their labels to this size.
I even tried applying a stackview around it, but i couldn't help much
Below is the code of cellForRow
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let post = posts[indexPath.row]
if let cell = tableView.dequeueReusableCell(withIdentifier: "FeedCell", for: indexPath) as? FeedCell {
cell.caption.text = ""
cell.configureCell(post: post)
cell.caption.sizeToFit()
cell.delegate = self
return cell
} else {
return FeedCell()
}
}
code for function in TableviewCell
func configureCell(post: Posts, img: UIImage? = nil) {
self.posts = post
self.caption.text = posts.caption
}
I am really unable to fix this. Any help is much appreciated.
How about using auto-layout to set a minimum width in percentage of a screen size IOS.
Auto-Layout constraint has that multiplier parameter that lets you use a fractional relationship between a superview and its subview.
While both the child view (Label) and its superview are selected, add "equal width". Then change the "multiplier" of the constraint you just added to the proportion you need. For example, for 30%
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "approve_cell");
let event = self.events[indexPath.row];
cell.textLabel?.text = event.name;
return cell;
}
I placed 2 images and a label in tableviewcell. When i run the app, images are not visible. What could be the reason?
Check that you are not using the basic style of the UITableViewCell because if you are then that style only includes labels.. no image views. Change it to subtitle or one of the details.
For reference, see: https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/TableView_iPhone/TableViewCells/TableViewCells.html
You probably forgot to set AutoLayoutConstraints of your image view. You could either add constraints to that image view through storyboard or through code. The other method is setting the frame of your image view in -(void)viewDidLayoutSubviews, because when you're using auto-layout, the layout of those views will be undefined if its constraints doesn't fulfill system's computing need. So you should either set right constraints or give a specific frame to those undefined views after all of the others has-constraints-views are arranged.
You creat cell in storyboard but you never use this cell created from storyboard. instead you manually creat it by UITableViewCell's designated initializer without override layout method of it.
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "approve_cell", for: indexPath)
let event = self.events[indexPath.row];
cell.textLabel?.text = event.name;
return cell;
}
You need to set either Autolayout or used Autoresizing. For autolayout just pinned the proper leading, trailing, top and bottom constraint.
a little new to Swift but as mentioned I have Table View in which each cell contains a button (in the form of an image) but I'm having trouble getting the correct cell size. The cell's height is always way to high, here's a picture of what I'm seeing.
as you can see the button's image / cell is elongated. How can I get each cell/button to be a more appropriate size?
Here's the code where I'm creating the cells
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SportsCell", forIndexPath: indexPath) as! SportTableViewCell
let index = mlbLogos.startIndex.advancedBy(indexPath.row)
cell.logoButton.setImage(mlbLogos.values[index], forState: UIControlState.Normal)
cell.logoButton.contentMode = UIViewContentMode.ScaleAspectFit
cell.logoButton.frame = CGRect(x: 0,y: 0,width: 32,height: 32)
return cell
}
EDIT: As far as storyboard constraints, I'm simply centering the UIButton in the prototype cell and expanding the button to be as large as the cell, then I just use the suggested constraints
This is what all of my cells look like. With some information displayed on right hand side of the cell. Instead of this design with a circular radius image on the left hand side and information on the right hand.I want my cells to be an Image and the information to be on top of that image.
This is the type of style I want on my cells to have, without the space in between images, I gave this an attempt by removing the information labels and using a horizontal Stack View on the cell.
But this is what the cells ended up looking like. For the radius of the image I didn't do it programatically I did trough the Identity Inspector
Keypath layer.cornerRadius
Type Number
Value 30
which makes the images round. Other than that there's no much code involved in the tableView, It's all mostly done trough the Main.StoryBoard, below I added some code showing how I configured the cells. Any tips or ideas on how I can accomplish this?
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! RestaurantTableViewCell
//* Configure the cell...
cell.nameLabel.text = restaurants[indexPath.row].name
cell.thumbnailImageView.image = UIImage(named: restaurants[indexPath.row].image)
cell.locationLabel.text = restaurants[indexPath.row].location
cell.typeLabel.text = restaurants[indexPath.row].type
cell.accessoryType = restaurants[indexPath.row].isVisited ? .Checkmark : .None
return cell
}
If you want the cell to show an image and then show text on top of that image, I'd suggest you set the image as the cell background view (rounding the corners if needed) and then populate your labels and accessory view as you are already doing.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let dictData : NSDictionary = arrayOfData.objectAtIndex(indexPath.row) as! NSDictionary
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = "THIS IS SOME TEXT"
if let image = dictData.objectForKey("Image"){
cell.backgroundColor = UIColor.clearColor()
let imageView = UIImageView(image: image as? UIImage)
imageView.layer.cornerRadius = 30.0
imageView.clipsToBounds = true
cell.backgroundView = imageView
}
return cell
}
That will give you text on top of an image :
So it looks like you use AutoLayout problem here is that you have right constraint. You can try removing constraint and set fixed width.
Step 1: Add UITableView and add constraints
Step 2: Add UIImageView and set it to "Aspect Fill" Otherwise your rounded corner image will not cover whole cell. (You can also set it to "Aspect fit" if you want). And add constraints as shown in image.
Step 3: Add labels and other information and also add constraints according to your requirement.