ios - UITableViewCell autolayout 支持 UIImageView 高度自动调整

 众大文化_724 发布于 2022-10-29 21:15

cell里面只有一个元素:UIImageView,我想要让它宽度占满cell,高度根据实际情况自动调整。

目前的代码如下:

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
        tableView.estimatedRowHeight = 150
        tableView.rowHeight = UITableViewAutomaticDimension
    }


}

extension ViewController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
        
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("fuckCell", forIndexPath: indexPath) as! fuckTableViewCell
        return cell
    }
    
}
class fuckTableViewCell: UITableViewCell {

    @IBOutlet weak var fuckImageView: UIImageView!
    @IBOutlet weak var fuckHeight: NSLayoutConstraint!
    
    override func layoutSubviews() {
        super.layoutSubviews()
        contentView.layoutIfNeeded()
        if let image = fuckImageView.image {
            fuckHeight.constant = fuckImageView.frame.width * (image.size.height / image.size.width)
        }
    }
    
}

imageView的约束如下(运行项目后,图片的高宽比不对,并且xcode提示约束冲突)。始终找不到哪里出了问题,麻烦熟悉的朋友解答下,非常感谢。

3 个回答
  • 同高同宽垂直、水平居中

    2022-10-31 19:11 回答
  • 你既然设置了leading,trailing,top,bottom的约束,imageview的height约束就不需要了吧?

    2022-10-31 19:12 回答
  • 在qq群里一位朋友的帮助下,终于达到预期效果且运行正常,非常感谢。

    我顺便把代码放到了github里,有需要的可以查看。由于水平有限,我不确认此方法是否存在未知大坑之类的,同时也希望在这一块熟悉的朋友给出更好的解决办法,或者提出有待改善的地方,谢谢!

    https://github.com/CrazyWisdom/ImageViewAutoHeight

    2022-10-31 19:12 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有