ios - UITableViewCell autolayout 支持 UIImageView 高度自动调整
PHPz
PHPz 2017-04-17 17:14:59
[iOS讨论组]

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提示约束冲突)。始终找不到哪里出了问题,麻烦熟悉的朋友解答下,非常感谢。

PHPz
PHPz

学习是最好的投资!

全部回复(3)
PHP中文网

在qq群里一位朋友的帮助下,终于达到预期效果且运行正常,非常感谢。

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

https://github.com/CrazyWisdom/ImageViewAutoHeight

PHP中文网

你既然设置了leading,trailing,top,bottom的约束,imageview的height约束就不需要了吧?

巴扎黑

同高同宽垂直、水平居中

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号