如何以编程方式设置TableViewCell中ImageView的固定大小?

4

我有一个问题,需要在tableviewcell中调整图片的大小。下面的图片显示,图片大小不均匀。

image

这里是我使用的代码。

 if noteImageIsAvailable == true {
        if let imageData = assignedNotePhoto?.photoData {
            if let image = Utilities.resizePictureImage(UIImage(data: imageData as Data)) {
                //added fix
                cell.imageView?.frame.size = CGSize(width: 36, height: 24)
                cell.imageView?.clipsToBounds = true
                //-----
                cell.imageView?.contentMode = .scaleAspectFill
                cell.imageView?.image = image
            }
        }
    }

我是一名有用的助手,可以为您翻译文本。

我在stackoverflow上读到了一个答案。它说我需要添加clipToBounds,但不幸的是它并没有起作用。请帮助我解决这个问题。谢谢。

TableView 代码

extension SettingNoteViewController: UITableViewDataSource, UITableViewDelegate {

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "reuseIdentifier")
    let keyPass = KeyHelper.NoteSetting.info[indexPath.row]
    let assignedNotePhoto = self.getNotePhoto(key: keyPass.key)
    let assignedNoteTextData = self.getNoteTextData(key: keyPass.key)?.value

    cell.contentView.backgroundColor = .black
    cell.textLabel?.textColor = .white
    cell.detailTextLabel?.textColor = .white
    cell.detailTextLabel?.numberOfLines = 0
    let noteImageIsAvailable = assignedNotePhoto?.photoData != nil

    if noteImageIsAvailable == true {
        if let imageData = assignedNotePhoto?.photoData {
            if let image = Utilities.resizePictureImage(UIImage(data: imageData as Data)) {
                //added fix
                cell.imageView?.translatesAutoresizingMaskIntoConstraints = false
                cell.imageView?.frame.size = CGSize(width: 36, height: 24)
                cell.imageView?.clipsToBounds = true
                //-----
                cell.imageView?.contentMode = UIView.ContentMode.scaleAspectFit
                cell.imageView?.image = image
            }
        }
    }
    cell.textLabel?.text = Menu.SettingNote.items[indexPath.row].value
    cell.detailTextLabel?.text = assignedNoteTextData ?? "noteSettingSubTitle".localized

    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.destination is InputMemoViewController {
        let vc = segue.destination as! InputMemoViewController
        vc.infoNoteKey = self.infoNoteKeyToPass
        vc.infoLabelText = self.infoLabelToPass
    }
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.infoNoteKeyToPass = KeyHelper.NoteSetting.info[indexPath.row].key
    self.infoLabelToPass = KeyHelper.NoteSetting.info[indexPath.row].label
    self.performSegue(withIdentifier: "showInputMemo", sender: self)
}

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

以下是应用@Kishan Bhatiya的解决方案时的输出图像。 output 第一张和第二张图片是风景照片,第三张图片是竖向的。 output2

你觉得在你的代码中加入 cell.imageView?.translatesAutoresizingMaskIntoConstraints = false 怎么样? - nwyyy
展示你的tableView代码。你是否已经创建了UITableViewCell? - Habin Lama
@nwyyy 你好,我也尝试添加了但仍然不起作用。 - user12758279
@HabinLama 你好,我已经添加了TableView的代码,但在我的storyboard中我没有添加tableviewcell - user12758279
移除 cell.imageView?.translatesAutoresizingMaskIntoConstraints = false 并检查,因为如果启用了 AutoLayout,则 frame 没有效果,或者您可以查看我的答案。 - Kishan Bhatiya
如果使用heightanchor和widthanchor无法解决问题,那么尝试在UITableViewCell中进行设计。 - Habin Lama
3个回答

3

您知道您的ImageView的大小。因此,您可以将UIImage调整为与ImageView相同的大小。

extension UIImage{
    func resizeImageWithHeight(newW: CGFloat, newH: CGFloat) -> UIImage? {
        UIGraphicsBeginImageContext(CGSize(width: newW, height: newH))
        self.draw(in: CGRect(x: 0, y: 0, width: newW, height: newH))
        
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newImage
    }
}

像这样使用

let img = originalImage.resizeImageWithHeight(newW: 40, newH: 40)
cell.imageView?.image = img

这里的“40 40”是我的ImageView的大小


2
当您添加cell.imageView?.translatesAutoresizingMaskIntoConstraints = false时,frame将不起作用,因此请尝试使用任何一个。
    let marginguide = contentView.layoutMarginsGuide


    //imageView auto layout constraints

    cell.imageView?.translatesAutoresizingMaskIntoConstraints = false

    let marginguide = cell.contentView.layoutMarginsGuide

    cell.imageView?.topAnchor.constraint(equalTo: marginguide.topAnchor).isActive = true
    cell.imageView?.leadingAnchor.constraint(equalTo: marginguide.leadingAnchor).isActive = true
    cell.imageView?.heightAnchor.constraint(equalToConstant: 40).isActive = true
    cell.imageView?.widthAnchor.constraint(equalToConstant: 40).isActive = true

    cell.imageView?.contentMode = .scaleAspectFill
    cell.imageView?.layer.cornerRadius = 20 //half of your width or height

最好在UITableViewCell中设置约束。


谢谢您的帮助。我尝试使用您的解决方案进行修复,它确实有效,但会影响“标题”和“副标题”的布局。请检查上面添加的图片。这是我使用您的解决方案时的输出结果。谢谢。 - user12758279
如果您正在使用AutoLayout设置约束,请将TitleSubTitle的前导锚点设置为单元格的imageView尾随锚点。 - Kishan Bhatiya
抱歉,怎么做呢? :D - user12758279
最好在UITableViewCell中创建这些约束。 - Kishan Bhatiya
1
谢谢你的帮助。现在它可以工作了。我只需要修复分隔符,因为当图像是横向时,它与“标题”和“副标题”不对齐。非常感谢你。 :D - user12758279

1

我有同样的问题,scaleAspectFit对我来说解决了问题。你可以尝试一下。

cell.imageView.contentMode = UIViewContentMode.scaleAspectFit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接