iOS TableView Multiline text - ios

I have this table and I want the lines to be multiline text.
How can I achieve this? This is the way I read everywhere.
This is my code to setup my cells:
let cell = tableView.dequeueReusableCellWithIdentifier("SchoolCell", forIndexPath: indexPath)
if searchController.active && searchController.searchBar.text != "" {
cell.textLabel?.text = filteredSchools[indexPath.row].name
} else {
cell.textLabel?.text = schools[indexPath.row].name
}
cell.backgroundColor = ColorsPlus.instance.VLDMediumBlue()
cell.textLabel?.textColor = UIColor.whiteColor()
cell.textLabel?.font = UIFont(name: "TitilliumWeb-Regular", size: 16.0)
cell.selectedBackgroundView?.backgroundColor = ColorsPlus.instance.VLDDarkBlue()
cell.textLabel?.numberOfLines = 0
cell.textLabel?.sizeToFit()

Add UITableViewCell in your tableView in storyboard.
Set number of lines equal to zero in interface builder. You are setting after cell has been instantiated and height already been calculated.
You should have autolayout enabled and constraints setup for the label, enough to determine the height of cell. In your case, set top, bottom , left and right constraint.
Set tableView.height = UITableviewAutomatic;
This should result in multi-line text with dynamic cell height.
Or if you are not interested in dynamic cell height, then simply increase UITableCellView height in tableView Delegate
override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
return 60.0;
}
or simply update the default height as below
self.tableView.rowHeight = 60.0

Related

UIStackView zero height although I have content in it

I have UIStackView in UITableViewCell and have four long text labels in it.
In first load I show only first label with 44 height in cell and hide other three and StackView shows properly.Then when I click on tableViewCell I need to expand cell and show other three labels. I show them and reload TableView but my StackView has zero height after that and all four label have zero height too. I hit this problem only with IOS 10.1 and when I use labels with short text StackView work well.
This is my code:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var cell = tableView.cellForRowAtIndexPath(indexPath) as! AboutUsTableViewCell
cell.firstLabel.hidden = isExpanded
cell.secondLabel.hidden = isExpanded
cell.thirdLabel.hidden = isExpanded
isExpanded = !isExpanded
tableView.reloadData()
}
Thank you all!
You should update table after changing isHidden properties. That's should do a trick.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var cell = tableView.cellForRowAtIndexPath(indexPath) as! AboutUsTableViewCell
cell.firstLabel.hidden = isExpanded
cell.secondLabel.hidden = isExpanded
cell.thirdLabel.hidden = isExpanded
isExpanded = !isExpanded
tableView.beginUpdates()
tableView.endUpdates()
}
Also, check this article about using UIStackView inside UITableView cells
Set the Labels number of lines to 0 and add below code to the viewDidLoad method.
self.tableView.estimatedRowHeight = 44.0 //or cell height
self.tableView.rowHeight = UITableViewAutomaticDimension

How to adjust label height and width in custom tableView Cell

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
}

UITableViewCell: get the exact width of UILabel in cell

I am having the problem when getting the correct width of the label in custom cell.
This is my cell in storyboard:
When the table is created, I understand that when cellForRowAtIndexPath is called, the cell is just created and not added to UITableView yet, so the width of the label is 304px. This causes the result like this:
After scrolling, the cell has been added to the UITableView so it shows correctly, with the width of the label is 164px.
Is there any way to know the exact width of cell/label before it is added to UITableView?
The constraints on the label: Leading, Trailing, Top and Height
Below is source code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: ArticleCell = tableView.dequeueReusableCellWithIdentifier("articleCell", forIndexPath: indexPath) as! ArticleCell
let item = array.objectAtIndex(indexPath.row) as! Article
cell.showDataForArticle(item, dateFormatter: dateFormatter)
return cell
}
func showDataForArticle(article: Article, dateFormatter: NSDateFormatter) {
self.titleLbl.text = article.articleTitle
titleHeightConstraint.constant = titleLbl.requiredHeight() <--- where problem happens
self.thumbnailImgView.imageLink(article.articleThumbnailLink!)
self.authorLbl.text = article.articleCreator
self.dateLbl.text = dateFormatter.stringFromDate(article.articlePubDate!)
}
extension UILabel {
func requiredHeight() -> CGFloat {
let frame = CGRectMake(0, 0, self.frame.size.width, CGFloat.max)
let label: UILabel = UILabel(frame: frame)
label.numberOfLines = 0
label.lineBreakMode = .ByWordWrapping
label.font = self.font
label.text = self.text
label.sizeToFit()
return label.frame.size.height
}
As far as trying to get the width of the label have you tried something alone the lines of
self.YourLabelName.bounds.width
You can have a label that would adjust its height based on the text it has to show using auto layouts.
1. For this to work you should not set static height for your cell, just add the below two delegates,
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 44;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
2. You should set top to bottom constraint for your cell,
In your case your header label should have TopSpace to Cell, LeadingSpace to ImageView, TrailingSpace to Cell (with standard spacing) and BottomSpace to AuthorLabel(with standard spacing).
3. The label you want with dynamic height as per text should have set the number of lines to 0 and LineBreakMode to Word Wrap.
Thats it, also find this links similar to your case,
Dynamic UITableViewCell content does not expand cell
Dynamically increase height of UILabel & TableView Cell?
Try calling titleLbl.requiredHeight() in func tableView(_ tableView: UITableView,
willDisplayCell cell: UITableViewCell,
forRowAtIndexPath indexPath: NSIndexPath) method

UITableViewAutomaticDimension not working properly with Subtitle UITableViewCells

I'm creating a 2 sections UITableView. The first section uses UITableViewCells with the Default style, the second uses Subtitle style. Both cells may have a multiline text label.
I've set the table's rowHeight to UITableViewAutomaticDimension.
As you can see from the screenshot below, UITableViewAutomaticDimension is respected only partially when using the Subtitle style: the height seems to fit the textLabel's height but not the detailLabel's one.
How can i make a Subtitle cell getting the right height?
Some code:
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.estimatedRowHeight = 80
tableView.rowHeight = UITableViewAutomaticDimension
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "defaultCell")
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "subtitleCell")
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section === 1 {
var cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "subtitleCell")
cell.textLabel?.numberOfLines = 0
cell.textLabel?.text = "A Long text..."
cell.detailTextLabel?.numberOfLines = 0
cell.detailTextLabel?.text = "A Long text..."
return cell
}
else {
var cell = tableView.dequeueReusableCellWithIdentifier("defaultCell") as! UITableViewCell
cell.textLabel!.text = "A long text..."
cell.textLabel?.numberOfLines = 0
return cell
}
}
I've tried to implement a subclass of UITableViewCell but I many problems with autolayout and section titles (a long story), so I wonder if I could fix the issue in a simpler way.
Just tried on Xcode 9 and iPhone 8 simulator, works very well.
code is here https://github.com/williamhqs/testSubtitleCellLayout

Adding Margins to Prototype Cells in UITableView

How can I add top, bottom, left, and right margin spacings between each individual prototype cell in UITableView? (storyboard) Seems there are different solutions for different versions of iOS and none for swift yet.
Current Cell
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("OptionCell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = self.options[indexPath.row]
cell.textLabel?.textAlignment = NSTextAlignment.Center
cell.layer.cornerRadius = 5.0;
cell.layer.borderColor = UIColor.whiteColor().CGColor
cell.layer.borderWidth = 1.5
cell.backgroundColor = UIColor.clearColor()
return cell
}
You can't set margins between cells, but you can make it look like there are margins by giving the cell a clear background color, and adding a subview (to which you would add any other subviews you need) that is inset from the edges of the cell by whatever margins you want. Give this view a background color, and turn off the cell separators. This can all be done in IB with no code if you choose.

Resources