Проблема в увеличении высоты ячейки на Подробнее UIButton - PullRequest
1 голос
/ 31 марта 2019

Возможно, мой вопрос повторяется. Но ни один из ответов не помог мне.

Теперь у меня есть UITableViewController с статическими ячейками и разным rowHeight в каждой статических ячейках .

И у меня есть UIButton , который должен помочь мне раскрыть полный текст в моей UILabel .

  • Первая строка имеет collectionView и высоту == 490.0
  • Во второй строке есть текст в UILabel , который я хочу показать в полном тексте, когда нажимаю UIButton и высоту по умолчанию 150,0, но мне нужно больше высоты, если текст будет иметь много текста
  • Третий ряд имеет collectionView и высоту == 150.0
  • Четвертый ряд имеет collectionView и высоту == 150.0
  • Пятый ряд имеет UILabel и высоту == 50.0

И мой экран Снимите то, о чем я говорю.

И мой код:

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

enter image description here

Ответы [ 2 ]

1 голос
/ 01 апреля 2019

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

Я нашел решение. Вы можете проверить мой рабочий демонстрационный проект здесь. .

1) Вам необходимо установить UILabel свойство setNumberOfLines = 0.

enter image description here

2) Создайте два ограничения @IBOutlet для увеличения и уменьшения вида и установите его priority.ех.priority = 750 и priority = 250 ( наоборот ).

  • первое ограничение для высоты исправления метки и его приоритет в раскадровке - 750.

    enter image description here

  • второе ограничение для метки снизу до ее суперпредставления и его приоритет в раскадровке 250.

    enter image description here

** см. Следующий код **

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()

    }
}

Надеюсь, этот ответ будет вам полезен.Удачного кодирования:)

0 голосов
/ 01 апреля 2019

Если вы установите свойство .amountOfLines на вашем UILabel на что-то вроде 5, это приведет к автоматическому усечению строки до 5 строк. Затем, когда пользователь нажимает кнопку «Подробнее», измените ее на 0, чтобы разрешить UILabel иметь бесконечные строки для отображения всего текста. Если вы уберете ограничение по высоте, установленное в ячейке, и автоматически настроите макет, он автоматически масштабируется.

Кроме того, если вы хотите анимировать расширение UILabel, вы можете найти это решение здесь: https://stackoverflow.com/a/34284563/5544222

...