Search code examples
iosswiftxcodeuitableviewnslayoutconstraint

Issue in increase height of cell on Read more UIButton


Perhaps my question repeats itself. But no one of the answers not helped mea.

Now I have UITableViewController with static cells and different rowHeight in each static cells.

And I have UIButton who should help me to reveal the full text in my UILabel.

  • The first row has implement collectionView and height == 490.0
  • The second row has text in UILabel that I want to show in full text when I click on UIButton and height on default 150.0, but me need more height if text will have a lot of text
  • The third row has implement collectionView and height == 150.0
  • The fourth row has implement collectionView and height == 150.0
  • The fifth row has UILabel and height == 50.0

And my screenShot what I'm talking about.

And my code:

class DetailTableViewController: UITableViewController {

    @IBOutlet weak var imagesCollectionView: UICollectionView!
    @IBOutlet weak var conveniencesCollectionView: UICollectionView! 
    @IBOutlet weak var equipmentAndOtherCollectionView: UICollectionView! 

    @IBOutlet weak var descriptionLabel: UILabel!
    @IBOutlet weak var readMoreButton: UIButton!

    var hall: Halls?

    let eq = ["Без проходной", "Циклорама", "Дневной свет", "Условия для семинаров", "Трехфазная нагрузка", "Генераторный свет", "Моноблоки", "Системы крепления"]
    let con = ["Wi-Fi", "Платная парковка", "Кофе-машина", "Душ", "Организация мероприятий"] // [""]

    var readMore: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.tableFooterView = UIView()
        tableView.estimatedRowHeight = 50
        tableView.rowHeight = UITableViewAutomaticDimension
        descriptionLabel.text = hall.description
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0: return 1
        case 1: return 1
        case 2: if eq.isEmpty || eq == [""] { return 0 } else { return 1 }
        case 3: if con.isEmpty || con == [""] { return 0 } else { return 1 } 
        default: return 1
        }
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.tableView.deselectRow(at: indexPath, animated: true)
    }

    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }

    @IBAction func readMoreButtonPressed(_ sender: UIButton) {
        readMore = true
        readMoreButton.isHidden = true
        //... code for reveal text
    }
}

hall.description has text Пространство рассчитано на различные виды съёмок. Также возможно проведение различных мастер-классов, семинаров, встреч и мероприятий. Профессиональное оборудование Profoto D1 500 Air (4 источника) и крепкими стойками Manfrotto. Великолепная акустика. Крепкая белоснежная циклорама с регулируемым подогревом пола.2 больших окна, дающие великолепный дневной жесткий и мягкий свет (солнечная сторона). Аудиосистема с USB и AUX. Уникальные декорации в LOFT стиле. Бесплатное гримерное место перед съемкой.Бесплатный wi-fi.

enter image description here


Solution

  • @Дмитрий Деникаев.

    I have found Solution. You can check my working demo project here..

    1) You need to set UILabel property setNumberOfLines = 0.

    enter image description here

    2) Create two @IBOutlet constraint for view increase and decrease and set its priority. ex. priority = 750 and priority = 250(vice versa).

    • first constrain for label fix hight and its priority in story board is 750.

      enter image description here

    • second constrain for label bottom to its superview and its priority in story board is 250.

      enter image description here

    **look into following code **

    In ViewTableViewCell.swift

      import UIKit
    
    class ViewTableViewCell: UITableViewCell {
    
    
        @IBOutlet var fixedHeightCon : NSLayoutConstraint!
        @IBOutlet var graterHeightCon : NSLayoutConstraint!
        @IBOutlet weak var lblText : UILabel!
        @IBOutlet weak var btnMore: UIButton!
        override func awakeFromNib() {
            super.awakeFromNib()
    
        }
    
        override func setSelected(_ selected: Bool, animated: Bool) {
            super.setSelected(selected, animated: animated)
    
            // Configure the view for the selected state
        }
    
    }
    

    in ViewController.swift

     import UIKit
    
    class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return  arrData.count
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell : ViewTableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ViewTableViewCell
            cell.btnMore.tag = indexPath.row
            cell.lblText.text  = arrData[indexPath.row]
            cell.layoutSubviews()
            return cell
    
        }
    
        @IBOutlet weak var tblView: UITableView!
        var arrData = ["This is long description.This is long description.This is long description.This is long description.This is long description.This is long description.This is long description.This is long description.This is long description.This is long description.This is long description.This is long description.This is long description.This is long description.","This is long description123.This is long description123.This is long description123.This is long description123.This is long description123.This is long description123.This is long description123.This is long description123.This is long description123.This is long description123.This is long description123.This is long description123.This is long description123."]
        override func viewDidLoad() {
            super.viewDidLoad()
            tblView.tableFooterView = UIView()
            tblView.rowHeight = UITableView.automaticDimension
            tblView.estimatedRowHeight = 77
            tblView.delegate = self
            tblView.dataSource = self
            // Do any additional setup after loading the view, typically from a nib.
        }
    
        @IBAction func changelabelHeight(sender:UIButton){
            let indexpath = NSIndexPath(row: sender.tag, section: 0)
            let cell = self.tblView!.cellForRow(at: indexpath as IndexPath) as? ViewTableViewCell
    
            if(cell!.fixedHeightCon.priority == UILayoutPriority(rawValue: 750)){
                cell!.btnMore.setTitle("Show Less", for: UIControl.State.normal)
                cell!.fixedHeightCon.priority = UILayoutPriority(rawValue: 250)
                cell!.graterHeightCon.priority = UILayoutPriority(rawValue: 750)
    
    
    
            }else{
                cell!.btnMore.setTitle("Read More", for: UIControl.State.normal)
                cell!.fixedHeightCon.priority = UILayoutPriority(rawValue: 750)
                cell!.graterHeightCon.priority = UILayoutPriority(rawValue: 250)
    
            }
            tblView.reloadData()
    
        }
    }
    

    I hope this answer helpful to you. Happy Coding :)