Как исправить динамическую высоту для отдельных ячеек, поскольку UIautodimensions не работает - PullRequest
0 голосов
/ 31 января 2019

Я создаю настенную страницу, такую ​​как твиттер или Facebook, в которой пользователь может публиковать на стене информацию, которая может включать изображение и просто текст.Таким образом, в зависимости от содержимого высота ячейки должна измениться, если запись состоит из одной строки, высота строки должна быть соответствующей.

Я пытался использовать UITableViewAutomaticDimensions, но он не работает с моим кодом, пожалуйста, помогите мне.

import UIKit

class wallPageViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var tableOfApps : UITableView?
var appNames: [String]? = []
var apps: [wallPageModel]?
var dynamic_height : CGFloat = 150.0
var addPost : UITextField?
var readMore : UITextView?


func loadTableOfApps(){

    //appNames = ["jkbajdba", "abfajfb", "akjbfkjag", "ahbfkajf" ]

    let provider = wallPageProvider()
    apps = provider.getApps()

    let tableHeight = view.frame.size.height


    tableOfApps = UITableView(frame: CGRect(x: 10, y: 60, width: 300, height: tableHeight))
    tableOfApps!.delegate = self
    tableOfApps!.dataSource = self
    tableOfApps?.separatorStyle = UITableViewCellSeparatorStyle.none


    //self.tableOfApps?.rowHeight = UITableViewAutomaticDimension
    //self.tableOfApps?.estimatedRowHeight = UITableViewAutomaticDimension
    print("load table of apps")

    view.addSubview(tableOfApps!)

}



override func viewDidLoad() {
    super.viewDidLoad()
    loadTableOfApps()
    loadAddPost()

    tableOfApps?.estimatedRowHeight = 150.0
    tableOfApps?.rowHeight = UITableViewAutomaticDimension

    view.backgroundColor = UIColor(red: 232/255, green: 234/255, blue: 246/255, alpha: 1.0)




    // Do any additional setup after loading the view.
}

func loadAddPost(){
    addPost = UITextField(frame: CGRect(x: 10, y: 20, width: 300, height: 30))
    addPost?.placeholder = "Stay safe, post a tip!"
    addPost?.isUserInteractionEnabled = true
    addPost?.borderStyle = UITextBorderStyle.roundedRect
    addPost?.autocapitalizationType = .none
    view.addSubview(addPost!)

    addPost?.addTarget(self, action: #selector(writeComment), for: UIControlEvents.touchDown)


}




func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    print("app coun\(apps!.count)")
    return apps!.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


    var cell : wallModelTableViewCell?

    cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? wallModelTableViewCell

    if cell == nil {
        cell = wallModelTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
    }

    let app = apps![indexPath.row]//reading the array of data hence provider

    //association of provider and view
    //this is the processs from where view can read the data from provide

    cell!.iconImageLabel!.image = app.icon
    cell!.titleLabel!.text = app.title
    cell?.backgroundColor = UIColor.white


    cell!.commentsLabel?.image = app.comments_Label
    cell?.commentsLabel?.center = CGPoint(x: tableView.frame.size.width/2, y: dynamic_height-20)

    cell?.likeButtonLabel?.image = app.likeButton
    cell?.likeButtonLabel?.center = CGPoint(x: (tableView.frame.size.width/2)-130, y: dynamic_height-20)
    /*cell?.likeButtonLabel?.leftAnchor.constraint(equalTo: tableView.leftAnchor, constant: 50)*/

    cell!.feedTextLabel!.text = app.feedText
    cell?.feedTextLabel?.sizeToFit()//so that it can expand the data more than two lines
    cell?.feedTextLabel?.backgroundColor = UIColor.clear


    //Limiting UIlabel to 125 characters
    if (cell?.feedTextLabel?.text.count)! > 125{
        /*
        let index = cell?.feedTextLabel?.text.index((cell?.feedTextLabel?.text.startIndex)!, offsetBy: 125)
        cell?.feedTextLabel?.text = cell?.feedTextLabel?.text.substring(to: index!)
        cell?.feedTextLabel?.text = cell?.feedTextLabel?.text.appending("...")*/
        //cell?.feedTextLabel?.attributedText = NSAttributedString(string: "...readmore")
    }


    cell?.layer.cornerRadius = 6.0
    cell?.isUserInteractionEnabled = false

    cell?.titleLabel?.isUserInteractionEnabled = true

    tableOfApps?.backgroundColor = UIColor.clear
    tableOfApps?.backgroundView?.isOpaque = false

    tableOfApps!.estimatedRowHeight = 150.0
    tableOfApps!.rowHeight = UITableViewAutomaticDimension


    print("table view cell for row")

    /*let tap: UITapGestureRecognizer  = UITapGestureRecognizer(target: self, action: #selector( self.labelAction(gesture:)))
    cell?.feedTextLabel?.addGestureRecognizer(tap)
    cell?.feedTextLabel?.isUserInteractionEnabled = true
    tap.delegate = self as! UIGestureRecognizerDelegate*/

    return cell!

}

/*@objc func labelAction(gesture: UITapGestureRecognizer){

}*/

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    print("height for row")
    return UITableViewAutomaticDimension
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return 150.0
}

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



 // MARK: - Navigation
 @objc func writeComment(){
 let addComment = addCommentViewController()
 navigationController?.pushViewController(addComment, animated: true)
 }
/*
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
 // Get the new view controller using segue.destinationViewController.
 // Pass the selected object to the new view controller.
 }
 */

}

Я хочу, чтобы каждая строка имела динамическую высоту, так как содержимое предоставляется пользователем, еслисодержимое содержит 150 символов, высота ячейки должна быть более 200, если содержимое содержит менее 125 символов, высота должна быть достаточной для чтения.

...