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提示约束冲突)。始终找不到哪里出了问题,麻烦熟悉的朋友解答下,非常感谢。
同高同宽垂直、水平居中
你既然设置了leading,trailing,top,bottom的约束,imageview的height约束就不需要了吧?
在qq群里一位朋友的帮助下,终于达到预期效果且运行正常,非常感谢。
我顺便把代码放到了github里,有需要的可以查看。由于水平有限,我不确认此方法是否存在未知大坑之类的,同时也希望在这一块熟悉的朋友给出更好的解决办法,或者提出有待改善的地方,谢谢!