andrew54068
andrew54068

Reputation: 1406

Two label align vertically in tableView cell auto resizing swift

Try to auto resizing two labels align vertically within a cell, is that possible?

In the storyboard, we have to set autolayout, since I want to auto resizing two labels(one is on top of another).

I can't set each height so that the storyboard doesn't know what is the height of these two labels so it shows an error for autolayout.

enter image description here

if I click "Add Missing Constraints" button it will add a height for "subtitle"

or I can set height for "title" rather than "subtitle",

or make "title" equal to "subtitle" it will still accept.

enter image description here

here is the result:

enter image description here

A workaround will be separate these two to a different cell. Any better solution? or am I just simply forget to do anything?

P.S. I'm using Xcode 8 with iOS 10.3.

Upvotes: 1

Views: 1812

Answers (1)

Tushar Sharma
Tushar Sharma

Reputation: 2882

Try setting out Proper constraints for both the labels-:

Storyboard-:

Constraints for first label-:

enter image description here

Constraints for second label-:

enter image description here

Controller class(use Automatic Dimensions for table view)-:

class ViewController1: UIViewController {

    var dataForTableView:[ProductImage]?

    @IBOutlet weak var secondTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        secondTable.estimatedRowHeight = 96
        secondTable.rowHeight = UITableViewAutomaticDimension
        // CHECK FOR DATA

        //print(dataForTableView?[0].url as Any)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension ViewController1 : UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return 1
    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! testingCell2
        cell.backgroundColor = UIColor.blue;
        cell.secondLabel.text = "agfhjsgfhjsgdshgfhjsfjhvhssajs hjfbvhjfbvjhfgafgfhlgkaghkfakfhkflbvhfbvhfvbhfv ah fvfhbvfjhvbfhdavhfvhv"
        return cell
    }

    // Number of sections in table

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }// Default is 1 if not implemented

    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return UITableViewAutomaticDimension
    }

}

Output-:

enter image description here

I hope that is what you looking for, let me know if any issues.Thanks

Upvotes: 3

Related Questions