user567
user567

Reputation: 3842

Dynamically set the size of TableViewCell with swift

I am setting heights of tableView cells statically for each cell with this code.

 func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

if let cell = modelCollection[collection.identifier] {
            if let _ = cell as? TiteCell{
              return 200
             }else if let _ = cell as? ParagraphCell{
              return 500
             } else if let _ = cell as? WebViewCell{
              return 1000
             }
}

I don't want to set the static value 1000 for the WebViewCell anymore but the height of the website requested with the WebView. The problem is that I am requesting the website in another class called WebViewCell after setting the height on the DetailViewController Class. Is that possible ?

Upvotes: 0

Views: 152

Answers (2)

Zonily Jame
Zonily Jame

Reputation: 5349

You could do it by doing this

Also don't forget to use NSLayoutConstraints cause this won't work without it

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

     if let cell = modelCollection[collection.identifier] {
            if let _ = cell as? TiteCell{
              return 200
             }else if let _ = cell as? ParagraphCell{
              return 500
             } else if let _ = cell as? WebViewCell{
              return UITableViewAutomaticDimension
             }
     }


 func tableView(tableView: UITableView, EstimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
     return 1000
}

Note: sorry if my answer formatting sucka. i'm using my phone at the moment

Upvotes: 0

Poles
Poles

Reputation: 3682

in the viewDidLoad use

tblView.rowHeight = UITableViewAutomaticDimension tblView.estimatedRowHeight = 200

and remove heightForRowAtIndexPath datasource method. Also don't forget to use AutoLayout in UITableViewCell.

For more info check http://www.appcoda.com/self-sizing-cells/

Upvotes: 1

Related Questions