I am using a UITableView and using the UITableViewCell Subtitle Style that is provided by Apple.
I am also using the Preferred Fonts so that they work with the Dynamic Type. If the user goes to Settings and changes the UI font size, it also affects the font in my view.
I am also allowing it to dynamically choose the row height based on the length of the text using row.estimatedRowHeight. This is great because with larger fonts and having multiple line text, the cells will adjust accordingly.
Using images is what is the problem. Images are of different sizes so scale them down. The scaling is sort of a hit or miss for the automatic cell height. It may not be done in time so the system calculation of the height may compute wrong.
My question then is, can I manually add constraints to the UITableViewCell's imageView property so that it has a set width and height of 88 pixels. This way, even if the picture isn't done resizing yet, it will at least calculate the height of the containing cell properly?
OR, maybe better to ask this: Is it possible to have a static width/height for the image when the cell and text labels resize dynamically based on content length and size?
Thanks!
There is a good library for creating UI dynamically. It's called Cartography
https://github.com/robb/Cartography
Here code that helps to create resizable cell by image view height:
import UIKit
import Cartography
class TableViewCell: UITableViewCell {
#IBOutlet weak var resizableImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func configurate() {
constrain(self.resizableImage) { view1 in
view1.width == view1.height
view1.top == view1.superview!.top
view1.bottom == view1.superview!.bottom
}
constrain(self.resizableImage) { view1 in
view1.height == 88
}
}
}
Related
I'm Working on TableViewCell and i'm using swift. As my Design I want a UIlabel in vertical align like "Confirm"
I have set this in Cell class
class AppointmentCell: UITableViewCell {
#IBOutlet weak var appointmentStatus: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let height = self.appointmentStatus.frame.size.height
let width = self.appointmentStatus.frame.size.width
appointmentStatus.transform = CGAffineTransform(rotationAngle: CGFloat.pi/2)
appointmentStatus.frame.size.width = height
appointmentStatus.frame.size.height = width
appointmentStatus.sizeToFit()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
But this solution is not Satisfied. This way taking more width in horizontal if i set constraints on width and height that is shrink the world in 3 characters "Con..." If I remove the constraints UIlabel take more space like...
This Screenshot From Iphone8 plus but on small Device IphoneSE label not showing.
My Question is how can I Achieve Vertical UILabel with correct frame size and constraints? How can I meet with my Design.
I know this is duplicate question there is more solutions on Stack overflow but i have not achieved my solution.
Thanks in Advance
I am trying to get a custom photo container with multiple UIImageViews to fit in my tableview cell. The view contains a variable number of images (1 ~ 9), and its height would change correspondingly from 1x to 3x imageHeight.
I used AutoLayout to define the top/bottom/leading/trailing margins with the tableview and the custom UIView inside, and to enable self-sizing cells, I have set
tableView.estimatedRowHeight = X
tableView.rowHeight = UITableViewAutomaticDimension
I initialize these cells with
tableView.register(nib: forCellReuseIdentifier:)
and in tableView(_ tableView: cellForRowAt:) method, I setup the cell with:
let cell = tableView.dequeueReusableCell(
withIdentifier: "test9cell",
for: indexPath) as! SocialFeedTableViewCell
cell.photoContainer.setup(with: urls)
cell.photoContainer.loadImages()
return cell
where setup() hooks each imageView in the container with a URL
func setup(with urls: [URL]) {
self.imageUrls = urls
for i in 0 ..< urls.count {
let imageView = UIImageView(frame: CGRect.zero)
self.addSubview(imageView)
self.imageViews.append(imageView)
}
self.setNeedsLayout()
}
func loadImages() {
self.imageViews.forEach { imageView in
imageView.frame = // Calculate position for each subview
imageView.sd_setImage(...) // Load web image asynchronously
}
}
Defining intrinsicContentSize for the view:
override var intrinsicContentSize {
let frameWidth = self.frame.size.width
var frameHeight: CGFloat
switch self.imageUrls.count { // range from 1...9
case 1...3:
frameHeight = frameWidth / 3
case 4...6:
frameHeight = frameWidth / 3 * 2
default:
frameHeight = frameWidth
return CGSize(frameWidth, frameHeight)
}
override func layoutSubviews() {
super.layoutSubviews()
self.imageViews.forEach { imageView in
imageView.frame = // Calculate position for each subview
}
}
The problem here is: after I set the initial intrinsicContentSize, the container's frame size changes in layoutSubviews() afterwards. Although by then I can position the imageView subviews correctly, the cell height will not be changed anymore.
Hope I am not making this problem more confusing. Could someone point out how would I resize the cell height AFTER modifying the contents of its UIView subview? Thanks!
There are a few things here that will be causing you some issues with dynamically sized cells.
You are adding multiple items to the cell but are not defining any auto layout constraints on the image views, so it does not know how to properly place / stack the items.
from the code above you are adding UIImageView with a frame of CGRectZero, without autulayout rules they will either stay zero or try to adjust to the contentsize when you add an image, but they wont adjust the cells height.
If you are loading images from the network they will likely be added/rendered after the tableviewcell has done its initial rendering. So you will likely need to cache the loaded images and reload the cell so that they can load in at the right time.
Now this last point is alot more complicated.
Dynamic UITableViewCell's calculate their height based on the autolayout rules of the content within them. You MUST have enough constraints from your content to the UITableViewCell's contentView property (to all edges) that give the cell enough information to place each item, calculate its overall height and width and therefore it is able to calculate the new height.
Using just one image isn't too bad for dynamic sized cells. but placing multiple items dynamically without any rules after the cell has initially rendered will not work.
You need to decide how these images should be laid out in your cell. once you have this you can look at adding the required constraints as you add the image views. Personally I would only add the image views once i have received each image.
Previously when I have done this I have cached the images once received and re-loaded the cell so that the image can be placed in the cell as it is rendered, allowing the tableview cell to calculate its height based off the image dimensions and constraints.
You may want to also consider using a collection view or merging the images together into a single image and using that in your cell. You could do this on device at runtime or server side if you have that kind of access to the images.
I'm using a UITableViewController with static cells and I want to make it so that the cells do not take up the entirety of the view. I want something more akin to this image: https://i.stack.imgur.com/4nO09.png
I can't quite figure out how to do so. I've been able to change the height thanks to self.tableView.contentInset, but I'm not sure how to change the width.
How would I do this?
EDIT:
Here's my Code for Fay007 as well as an image.
import UIKit
class ContactFormViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Sets the background images
if let patternImage = UIImage(named: "Pattern") {
view.backgroundColor = UIColor(patternImage: patternImage)
}
}
override func viewWillAppear(_ animated: Bool) {
let numberOfRows: CGFloat = CGFloat(self.tableView.numberOfRows(inSection: 0))
let headerHeight: CGFloat = (self.view.frame.size.height - (self.tableView.rowHeight * numberOfRows)) / numberOfRows
self.tableView.contentInset = UIEdgeInsetsMake(headerHeight, 0, -headerHeight, 0)
}
http://imgur.com/a/Q2kfH
The first image I linked has its cells away from the left/right edges, as in my comment I explained I believe they did using autolayout. Since the tableview is a subview of the UIView of the UIViewController, I believe one would be able to assure that. however, when using a UITableViewController, which is required to use static cells in a UITableView, there is no UIView parent.
One easy way of doing this is as follows: In storyboard, or interface builder, add a UIView subview to the UITableviewcell. Create constraints that define your desired distance of this subview to the edges of the cell.
To add rounded corners, you can do so within awakeFromNib by setting the cornerRadius of the subview's layer property to your desired radius.
I know how to make a custom self sizing cell. But for some reason I'm facing challenges when trying to make a default one multi-line.
What I currently want is a cell which only has one label. So the default one with a built-in style "Basic" seems to be the best solution for something as simple as that. However it only shows 2 lines of text.
My current set-up: a static UITableView and a UITableViewController containing outlets to some of the cells that need to be configured.
Things I tried:
set number of lines to 0
set table view's row height to UITableViewAutomaticDimension
override heightForRowAtIndexPath so that it always returns UITableViewAutomaticDimension
call sizeToFit, setNeedsLayout, layoutIfNeeded on the cell and/or content view and/or text label
set custom cell height to 0 in storyboard
increase vertical and horizontal content hugging priorities for the label
EDIT:
I guess I wasn't really clear about what exactly is the problem. I'm not using a custom cell. I'm trying to get away with the basic one.
This means you can't add any constraints to its label. Sure, you can programmatically but since everything is managed internally for Apple's built-in styles it may result in a conflict.
Additional details:
At this point (as I mentioned above) I have a UITableViewController with outlets to specific cells: #IBOutlet weak var descriptionCell: UITableViewCell!
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
Is it really possible? Since I already spent too much time trying to avoid making a custom cell I'll finally go make it. Anyway any solution is welcome.
It's no need to do following two.
call sizeToFit, setNeedsLayout, layoutIfNeeded on the cell and/or content view and/or text label
set custom cell height to 0 in storyboard
And you should check you label's constraints. For example, it should has fixed width at run time and has constraints with cell's top and bottom. So the cell will grow itself.
Try this approach:
Set number of lines to 0
Set table view's row height to UITableViewAutomaticDimension
Override heightForRowAtIndexPath so that it always returns UITableViewAutomaticDimension
NsLayConstraints for label:
top = cell.top
bottom = cell.bottom
leading = cell.leading.padding
trailing = cell.leading.padding (Padding is optional)
It works for me. All you need to do in your code is
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 44.0 // or whatever height is closest to what your cells will be
tableView.rowHeight = UITableViewAutomaticDimension
}
Everything you listed after "set table view's row height to UITableViewAutomaticDimension" is not necessary. Just set number of lines in your cell's label to 0 like you did and include the code above.
I have UITableView with UITableViewAutomaticDimension and some estimatedRowHeight. For this table I am using custom UITableViewCell which contains some label and custom UIView with overridden intrinsicContentSize(). Constraints setup is correct and table is able to determine actual height for each row. So far so good.
Now I started to modify internal logic of my custom view to adapt it's appearance based on available width i.e. when table cell size is not wide enough my view can rearrange subviews to fit new limitation and this have impact to resulting height, so I have code like that:
var internalSize: CGSize = ...
override func intrinsicContentSize() -> CGSize {
return internalSize
}
override func layoutSubviews() {
super.layoutSubviews()
fitIntoWidth(frame.size.width)
}
private func fitIntoWidth(width: CGFloat) {
let height = // calculate based on content and width
internalSize = CGSizeMake(width, height)
invalidateIntrinsicContentSize()
}
Now, when I populate table view, intrinsicContentSize() returns some desired value but it is not good fit for current layout, then control goes to layoutSubviews() where size get recalculated and system again calls intrinsicContentSize() and now it returns good value. However, first time table loads data and cell heights calculated based on incorrect intrinsicContentSize() values. If I call reloadData() again all becomes fine and layout is also ok for all upcoming cells in table.
Where is my mistake and how to modify code to make cell sizing work correctly without calling reloadData() twice?