【问题标题】:UIImageView not resizingUIImageView 没有调整大小
【发布时间】:2025-12-23 02:45:11
【问题描述】:

我正在使用带有 Xcode 8 的 Swift 3.0,但我在调整图像大小时遇到​​了一些问题。这是我设置 UIImage 框架的代码。

  open func setData(_ data: Any?, image: String) {

    self.textLabel?.font = UIFont.boldSystemFont(ofSize: 10)
    self.textLabel?.textColor = UIColor(hex: "000000")
    if let menuText = data as? String {
        self.textLabel?.text = menuText
    }

    self.imageView?.contentMode = UIViewContentMode.scaleToFill
    self.imageView?.frame = CGRect(x: 12, y: 8, width: 10, height: 10)
    self.imageView?.image = UIImage(named: image)   
    self.imageView?.clipsToBounds = true

}

这是我在 tableView 中调用函数的地方。我对设置图像没有任何问题,但只有调整大小。当我使用较小的图像时,图像会更小,当我使用较大的图像时,图像会变大,它不会调整大小。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = BaseTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: BaseTableViewCell.identifier)
        cell.setData(menus[indexPath.row], image: images[indexPath.row])
        return cell 
}

【问题讨论】:

  • 如果这是默认表格单元格内的 imageView,那么它可能有一些默认约束。您是否尝试过创建自己的单元子类?
  • @mag_zbc 现在我要试试这个

标签: ios swift3 uiimageview xcode8


【解决方案1】:

我已经解决了这个问题,方法是使用这个 resize 函数来调整我的图像大小,然后放在 ImageView 中

func imageResize(image:UIImage,imageSize:CGSize)->UIImage
{
    UIGraphicsBeginImageContextWithOptions(imageSize, false, 0.0)
    [image .draw(in: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))]
    let newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext()
    return newImage!
}

【讨论】:

    【解决方案2】:

    如果您使用的是 uitableview 单元格的默认图像视图,您将无法调整它的大小。一些默认约束已经存在。

    你有两个选择:

    1. 创建 uitableview 单元格的子类并使用您自己的图像视图(不要创建名称为 imageView 的插座,尝试其他方法)。

    2. 使用https://*.com/a/45100626/5383852调整图像大小

    【讨论】: