【问题标题】:How to set fix ImageView size inside TableViewCell programmatically?如何以编程方式在 UITableViewCell 内设置修复 ImageView 大小?
【发布时间】:2020-05-28 16:40:00
【问题描述】:

我有这个问题,我需要修复 tableviewcell 内图像的大小。下图显示图像尺寸不均匀。

这是我使用的代码。

 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,但不幸的是它不起作用。请帮我解决这个问题。谢谢

表格视图代码

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 解决方案时的输出。

第一张和第二张图片是横向的,第三张是纵向的

【问题讨论】:

  • 在您的代码中添加cell.imageView?.translatesAutoresizingMaskIntoConstraints = false 怎么样?
  • 显示您的 tableView 代码。你有没有创建 UITableViewCell?
  • @nwyyy 嗨,我也尝试添加它,但还是不行
  • @HabinLama 嗨,我添加了 TableView 的代码,我没有在我的故事板中添加 tableviewcell
  • 删除cell.imageView?.translatesAutoresizingMaskIntoConstraints = false并检查,因为如果AutoLayout启用,那么frame没有效果或者你可以检查我的答案

标签: ios swift uitableview uiimageview


【解决方案1】:

当你添加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中设置约束

【讨论】:

  • 感谢您的帮助。我尝试使用您的解决方案修复它,它可以工作,但它会影响 TitleSubTitle 的布局。请检查上面添加的图像。这是我使用您的解决方案时的输出。谢谢
  • 如果使用AutoLayout 设置约束,则将TitleSubTitle 的前导锚设置为单元格的imageView 尾随锚
  • 对不起,怎么办? :D
  • 最好在UITableViewCell中创建这些约束
  • 感谢您的帮助。现在可以了。我只需要修复分隔符,因为当图像是横向时它与titlesubtitle 不对齐。太感谢了。 :D
【解决方案2】:

我有同样的问题,scaleAspectFit 为我解决了。你可以试试

cell.imageView.contentMode = UIViewContentMode.scaleAspectFit

【讨论】:

    【解决方案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 大小

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多