How to change tableview cell height according to label text swift?
Considering you have already applied constraints on the label. And also set your number of lines to 0. And then paste the following code in viewDidLoad method
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
Dynamically change cell height according to label text
The bottom anchor needs to be set:
cevapLabel.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
Swift Automatic Row Height for Subtitle Cell
By using this code from https://stackoverflow.com/a/40168001/4045472 and define the cell as:
class MyTableViewCell: UITableViewCell {
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
self.layoutIfNeeded()
var size = super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)
if let textLabel = self.textLabel, let detailTextLabel = self.detailTextLabel {
let detailHeight = detailTextLabel.frame.size.height
if detailTextLabel.frame.origin.x > textLabel.frame.origin.x { // style = Value1 or Value2
let textHeight = textLabel.frame.size.height
if (detailHeight > textHeight) {
size.height += detailHeight - textHeight
}
} else { // style = Subtitle, so always add subtitle height
size.height += detailHeight
}
}
return size
}
}
And change the cell custom class in storyboard to MyTableViewCell will set the correct size automatically.
In the table view datasource's tableView:cellForRow: function, after set the labels' text, call cell.setNeedsLayout()
to force it adjust layout.
Change the height of a TableViewCell depending on if it has an image
I ended up adding this code to the tableview cellforrowat index path function in order to get the images rendering correctly.
let imageIndex = posts[indexPath.row].mediaURL
let url = NSURL(string: imageIndex)! as URL
if let imageData: NSData = NSData(contentsOf: url) {
let image = UIImage(data: imageData as Data)
let newWidth = cell.MediaPhoto.frame.width
let scale = newWidth/image!.size.width
let newHeight = image!.size.height * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
image!.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
cell.MediaPhoto.image = newImage
cell.MediaPhoto.contentMode = .scaleToFill
cell.MediaPhoto.clipsToBounds = true
How to use dynamic height of UITableViewCell in auto-layout and move other views to up when bottom view is hidden?
At first, make the height of UITableViewCell to UITableView.automaticDimension
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
Embed all of your questionLabels in a UIStackView
(vertical) excluding bottomLabel
. Set AutoLayoutConstraint between UIStackView
and bottomLabel
.
Set the numberOfLines
property of UILabel
s to 0(zero).
Set the Distribution of the UIStackView
as Fill
Then, in your tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
method hide the labels. And it will automatically handle the spaces between UILabel
s
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCell
cell.questionLabel1.text = labelOneText[indexPath.row]
cell.questionLabel2.text = labelTwoText[indexPath.row]
cell.questionLabel3.text = labelThreeText[indexPath.row]
if labelOneText[indexPath.row] == "" {
cell.questionLabel1.isHidden = true
}
if labelTwoText[indexPath.row] == "" {
cell.questionLabel2.isHidden = true
}
if labelThreeText[indexPath.row] == "" {
cell.questionLabel3.isHidden = true
}
return cell
}
Final Output:
Dynamically adjust the height of the tableview cell based on content - iOS Swift
Use custom cell and labels.
Set up the constrains for the UILabel. (top, left, bottom, right)
Set lines of the UILabel to 0
Add the following code in the viewDidLoad method of the ViewController:
tableView.estimatedRowHeight = 68.0
tableView.rowHeight = UITableView.automaticDimension
// Delegate & data source
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableView.automaticDimension;
}
Swift 4:
// Delegate & data source
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
Swift 4.2:
// Delegate & data source
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
Related Topics
How to Set Kerning (Spacing Between Characters) on Uinavigationbar Title - Swift or Objective-C
Avplayer Not Full Screen in Landscape Mode Using iOS Swift
Libmobilegestalt Mobilegestalt.C:890: Mgisdeviceoneoftype Is Not Supported on This Platform
Swift 4 Get Error Code from Error
Swift: Load Custom Uiview from Xib Programmatically
Embedding a Uitableview as a Container View Within a Uiviewcontroller
Exc_Bad_Access in Parent Class Init() with Xcode 10.2
Items in File Provider Extension for iOS 11
Setup a Collectionview with "Tag"-Like Cells
Firebase Get Child Id Swift iOS
How to Center a Label Horizontally for All iOS Devices in Swift
How to Enable Only Numeric Digit Keyboard iOS Swift
Skspritenode Does Not Let Touches Pass Through When Isuserinteractionenabled False
How to Keep the Header Cell Moving with the Tableview Cells in Swift 2.0
Value of Type 'Error' Has No Member 'Code'
iOS Media Playback Controls Notification
Swift Nfc Mifare - Nfciso7816Apdu Sendmifare Command Not Supported
iOS How to Correctly Handle Orientation When Capturing Video Using Avassetwriter