DionizB
DionizB

Reputation: 1507

UIImageView not resizing

I'm using Swift 3.0 with Xcode 8 and I'm having some problems with image resizing. Here is the code where i set my UIImage frame.

  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

}

And here is where I call my function inside my tableView. I don't have any problem with setting the image, but ONLY with resize. When i use smaller images, the image is smaller, when i use bigger images, the image gets bigger, it doesnt resize.

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 
}

Upvotes: 1

Views: 2065

Answers (2)

Vidhan Nandi
Vidhan Nandi

Reputation: 53

If you are using default image view of uitableview cell than you won't be able to resize it. Some default constraints are already there.

You have two options :

  1. create a subclass of uitableview cell and use your own image view (don't create the outlet with name imageView, try something else).

  2. Resize the image using https://stackoverflow.com/a/45100626/5383852

Upvotes: 1

DionizB
DionizB

Reputation: 1507

I have solved it by using this resize function to resize my image and then place in the 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!
}

Upvotes: 1

Related Questions