I have a expandable tableView, in which when i expand a section, than there are three cell. On firth Cell there is only name and in second cell. It have a big content. Now I want to auto adjust this label height and width according to content.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tblView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomTableViewCell
let dataArrayTblView = dataArrayForTableView
let titleName = dataArrayTblView.valueForKey("name")
let dueDate = dataArrayTblView.valueForKey("deadlinedate")
let description = dataArrayTblView.valueForKey("description")
cell.titleLabel.text = titleName[indexPath.row] as AnyObject! as! String!
cell.dueDateLabel.text = dueDate[indexPath.row] as? String
cell.descriptionLabel.text = description[indexPath.row] as? String
cell.descriptionLabel.sizeToFit()
cell.textLabel?.backgroundColor = UIColor.clearColor()
cell.selectionStyle = .None
return cell
}
But not getting complete content
Try to set this. It will automatically adjust the height of the row for you. If it is not working, then you have something wrong with your constraints inside your storyboard.
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 40
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
You should use UITableViewAutomaticDimension as row height something like,
// this should be set in viewDidload
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140
for that you must use autolayout and should set proper constraints to your label in cell.
Constraint should be in linear chain, I mean your label's top and bottom both constraint must be set and your label should resize according to content so your cell will resize accordingly!
You can refer Self-sizing Table View Cells by Raywenderlich !
Put below in viewDidLoad and set autolayout as per below screenshots.
tblview.rowHeight = UITableViewAutomaticDimension
tblview.estimatedRowHeight = 44
Screenshot 1
Screenshot 2
Screenshot 3
Screenshot 4
Use heightForRowAtIndexPath method to adjust height of row. Calculate
size of string with boundingRectWithSize this method. example:
Try This:
if let YOUR_STRING:NSString = str as NSString? {
let sizeOfString = ns_str.boundingRectWithSize(
CGSizeMake(self.titleLabel.frame.size.width, CGFloat.infinity),options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: lbl.font], context: nil).size
}
Related
I wrote such extension to display my data in UITableview. But sometimes my data can contain more than 1 line and I need to create something to display full content. How could I change my code (below) to do it?
extension ViewController: UITableViewDataSource, UITableViewDelegate {
// Define no of rows in your tableView
func tableView(_ chatHistoryTable: UITableView, numberOfRowsInSection section: Int) -> Int {
return messagesData.count
}
func tableView(_ chatHistoryTable: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = chatHistoryTable.dequeueReusableCell(withIdentifier: "userMessage")! as UITableViewCell
cell.textLabel!.text = messagesData[indexPath.row]
cell.textLabel!.textAlignment = .right
return cell;
}
}
I think that I should write something for UITableViewCell too, but I don't know, am I correct.
Please help me with this question.
in here you need to follow two changes.
initially set the estimate height and auntomaticdimension for Self Sizing Cell, on your page loads call the following line.
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableView.automaticDimension
for e.g
#IBOutlet weak var yourTableviewName: UITableView!{
didSet{
yourTableviewName.tableFooterView = UIView()
yourTableviewName.estimatedRowHeight = 44.0
yourTableviewName.rowHeight = UITableView.automaticDimension
}
}
secondary for your word wrap and numberOfLines for your lables. follow the below line on your cellforRow method
func tableView(_ chatHistoryTable: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = chatHistoryTable.dequeueReusableCell(withIdentifier: "userMessage")! as UITableViewCell
cell.textLabel!.numberOfLines = 0
cell.textLabel!.lineBreakMode = .byWordWrapping
cell.textLabel!.text = messagesData[indexPath.row]
cell.textLabel!.textAlignment = .right
return cell;
}
}
Step 1. Add a chain of unbroken vertical constraints in Custom Table View Cell
Step 2. Set the cell estimated height
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
Step 3:Make the label support multiple lines
textLabel.LineBreakMode = UILineBreakMode.WordWrap;
textLabel.Lines = 0;
I use dynamic height cells for my UITableView with this code:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "QuestionsCell", for: indexPath) as! QuestionsCell
cell.label1.text = ""
cell.label2.text = ""
cell.label1.text = some text from array
cell.label2.text = some text from array
cell.label1.lineBreakMode = .byWordWrapping
cell.label1.numberOfLines = 0
cell.label1.sizeToFit()
return cell
}
Then I've pinned all constraints in Storyboard for each element (top, bottom, leading and trailing). On iPhone everything works fine, but on iPad when I scroll the UITableView this is happening (dynamic label height):
sizeToFit() only makes cell1 as big as it needs to be for the text.
You also need to use automatic height sizing for the table view cells.
In viewDidLoad,
self.tableView.rowHeight = UITableViewAutomaticDimension
You will also want to make sure you have a vertical constraint from your bold label to the "12 days ago" label, to ensure there is always vertical space between them, so they don't overlap.
you need to implement this delegate method:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
if this does not work then check if there is vertical spacing constraints between top textView and bottom textView.
I'm having a lot of issues getting my custom cells to use the dynamic row height.
Here is the xib of my custom cell.
In viewDidLoad for my table view, I set these values:
self.tableView.estimatedRowHeight = 80.0
self.tableView.rowHeight = UITableViewAutomaticDimension
but it doesn't seem to use the dynamic size when it loads the table.
Below is my cellForRowAtIndexPath function.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Configure the cell...
let cell = Bundle.main.loadNibNamed("RedditCell", owner: self, options: nil)?.first as? RedditPostCellTableViewCell
let post = self.model?.getPostAt(index: indexPath.row)
cell?.title.text = post?.title
cell?.author.text = post?.author
cell?.upvotes.text = "\(post?.upvotes ?? -1)"
return cell!
}
I can't figure out why this isn't working. Any help would be appreciated!
Please try to set the height in the heightForRowAt
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
self.tableView.estimatedRowHeight = 80
return UITableViewAutomaticDimension
}
You don't need to pre-calculate the height. The problem is with your constraints in your custom UITableViewCell. Your constraints should be set up the way to force UITableViewCell to expand to show the whole label or any other content. Just setup constraints similar to my short example project: https://www.transfernow.net/216sw6l1bler?lng=en, and cell height will be automatically set, as you expected.
Screenshot:
In addition to setting the constraints so that the height of all of the elements in the cell + padding can be used to calculated the overall cell height, you must set the number of lines of your labels to zeros and set them to word wrap if these must grow based on content as well.
I am trying to figure out how get the correct height for my tableview cell that contains a uitextview so that all the content in the uitextview will be display. The textview is not editable and not scrollable, which means that the string for the uitextview is known. I tried simply returning the height of the tableview cell that is in the storyboard in heightForRowAtIndexPath but that cuts off the content if it is too large. I also tried calculating the height for the textView in heightForRowAtIndexPath but it throws an error at runtime:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let cellInfo = UserCellsArray[indexPath.section]
switch cellInfo {
case .userInfo: return 104
case .ubio:
let cell = tableView.dequeueReusableCellWithIdentifier(cellInfo.description, forIndexPath: indexPath) as! UserProfileTableViewCell //error
let oldHeight = cell.userBio.frame.size.height
cell.userBio.text = self.bio
var bodyframe = cell.userBio.frame
bodyframe.size = cell.userBio.contentSize
let newHeight = cell.userBio.contentSize.height
return tableView.rowHeight - oldHeight + newHeight
}
}
Here is what you need to do:
Need to use auto layout in your cell and set up appropriate constraints for UILabel. Since we want to resize the UILabel to fit the text set to it, we will set the number of lines value to 0. And then set the leading, trailing, bottom and top constraints to the UILabel. Please see screenshots here:
In your Table View controller > viewDidLoad call these two lines:
tableView.estimatedRowHeight = 50.0 //Give an approximation here
tableView.rowHeight = UITableViewAutomaticDimension
and also implement delegate method:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
return UITableViewAutomaticDimension
}
This is my layout.The Label's top to the ContentView's top is 58pt.The numberOfLine of the Label is 0.So it can Enter automatically.
And I want the Height of every cell is 58.0+10.0+the height of label.
I have tried this code.
TV.estimatedRowHeight = 68
TV.rowHeight = UITableViewAutomaticDimension
But didn't work.
And then tried this code.
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let cell = tableView.cellForRowAtIndexPath(indexPath) as! CommentDetailCell
return 68.0 + cell.Comment.frame.size.height
}
Didn't work again.
And then try this!To create a array to store the height of every cell's labelHeight.
var CommentHeightA:[CGFloat] = [60.0,60.0,60.0,60.0]
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell:CommentDetailCell = tableView.dequeueReusableCellWithIdentifier("cell") as! CommentDetailCell
cell.UserImg.image = UIImage(named: UserImgA[indexPath.row])
cell.AtNum.text = AtNumA[indexPath.row]
cell.LikeNum.text = LikeNumA[indexPath.row]
cell.isLike.image = UIImage(named: isLikeA[indexPath.row])
cell.Comment.text = CommentA[indexPath.row]
CommentHeightA[indexPath.row] = cell.Comment.frame.size.height
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 68.0 + CommentHeightA[indexPath.row]
}
And :( all the ways above is failed.
So how can I get what I want?
Update:
I have added the bottom constraint and used the 1st way.
This is the result.Only the 1st row has a appropriate height.
You need to add a bottom constraint from the comment label to the content view. Then add the following code:
TV.estimatedRowHeight = 68
TV.rowHeight = UITableViewAutomaticDimension
It will work,