0

I'm trying to use an external image as a tab bar button. I've seen this with few apps so I thought I'd give it a go.

HackingWithWift mentioned using SDWebImage

import SDWebImage
import UIKit

class ViewController {

    let imageView = UIImageView()
    var tabBar = UITabBar()

    // viewDidLoad

    imageView.sd_setImage(with: URL(string: "https://randomuser.me/api/portraits/men/32.jpg"), placeholderImage: UIImage(named: "tablogo")) { image, error, foo, url in
        
        print(image, error, foo, url)
        
        // Assume no errors!
        
        let img = self.resizeImage(image: image!, newWidth: 25)
        
        let itemAvatar = UITabBarItem(title: "Profile", image: img, selectedImage: img)

        
        self.tabBar.frame = CGRect(x: 0, y: self.view.frame.height - 75, width: self.view.frame.width, height: 50)
        self.tabBar.items = [self.itemAvatar]
        self.view.addSubview(self.tabBar)
    }
}

Nothing happened so I thought I needed to resize the image first so I found this answer.

func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {
    let scale = newWidth / image.size.width
    let newHeight = image.size.height * scale
    UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
    image.draw(in: CGRectMake(0, 0, newWidth, newHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage!
}

When the view loaded, my tab bar is shown with a square and no image.

enter image description here

How can I resolve this?

TylerP
  • 9,600
  • 4
  • 39
  • 43
Sylar
  • 11,422
  • 25
  • 93
  • 166

1 Answers1

1

Try to add RenderingMode to your image

UIImage(named: "tablogo")?.withRenderingMode(.alwaysOriginal)
Fabio
  • 5,432
  • 4
  • 22
  • 24
  • 1
    I'm glad to help you :) if I can advise you declare your image like this guard let myImage = image else { return } in line below you can remove ! operator to prevent crash: let img = self.resizeImage(image: myImage, newWidth: 25) – Fabio Nov 12 '22 at 15:18