UITableViewCell内的xibView

时间:2018-12-27 11:48:28

标签: swift uitableview dynamic uiview xib

我有一个名为PodView的自定义视图,该视图应具有动态高度, 我想将此视图作为TableViewCell中的子视图, 在我连接到PodView类的灰色视图中。 但由于某种原因,模拟器也无法显示该单元格 有什么想法吗?

View Image

import UIKit

class PodView: UIView {

    @IBOutlet var view: UIView!

    @IBOutlet weak var podImage: UIImageView!
    @IBOutlet weak var podTitle: UILabel!
    @IBOutlet weak var podDescription: UILabel!
    @IBOutlet weak var podImageHeight: NSLayoutConstraint!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        UINib(nibName: "PodView", bundle: nil).instantiate(withOwner: self, options: nil)
        addSubview(view)
    }

    func setPod(image: UIImage?, title: String!, description: String?, viewWidth: CGFloat!) {
        if image != nil{
            podImage.image = image!
            let ratio = image!.size.height / image!.size.width
            let height = (viewWidth) * ratio
            if height > 435{
                podImageHeight.constant = 435
            } else {
                podImageHeight.constant = height
            }
        }
        else{podImageHeight.constant = 0}
        podDescription.text = description
        podTitle.text = title
    }

}

View Image

import UIKit
struct Post{
    var image: UIImage?
    var title: String?
    var description: String?
}

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    var posts: [Post] = [Post(image: #imageLiteral(resourceName: "image4"), title: "post0", description: "description0"),
                         Post(image: #imageLiteral(resourceName: "image0"), title: "post1", description: "description1"),
                         Post(image: #imageLiteral(resourceName: "image0"), title: "post2", description: "description2")]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.estimatedRowHeight = 1000
        self.tableView.rowHeight = UITableView.automaticDimension
    }
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return posts.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let post = posts[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! TableViewCell
        cell.podView.setPod(image: post.image, title: post.title, description: post.description, viewWidth: UIScreen.main.bounds.width - 40)
        cell.setPost(caption: "This long caption with 2.0 rows, This long caption with 2.0 rows")
        cell.layoutIfNeeded()
        return cell
    }
}

View Image

0 个答案:

没有答案