ios - 从服务器加载图像到标签栏项目

标签 ios swift xcode

我从服务器加载了一张图片,并试图将它放在 UITabBarItem 上,但它只显示一个灰色方 block 。我已经将图像渲染模式设置为原始但不起作用...

谢谢你的帮助

downloader.imageDownloader?.downloadImage(with: URL(string: GlobalSetting().initUser().photoPath)!, options: .highPriority, progress: { (receivedSize, expectedSize, url) in
            print(receivedSize as Int)
        }, completed: { (image, data, error, success) in
            let newImage = image?.resizeImageWith(newSize: CGSize(width: 20, height: 20))
            newImage?.withRenderingMode(.alwaysOriginal)
            self.tabBar.items![1].image = newImage
        })

GlobalSetting 是我保存 URL 照片“http://api.humancloudz.com/photo/comp_abc/avatar-A18002.png”的地方

最佳答案

我不知道你的代码哪里有问题,因为我只看到了其中的一部分。我尝试创建 TabBarController,尝试在 viewDidAppear 中加载图像,一切正常。试试我的代码

class TabBarController: UITabBarController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    guard let url = URL(string: "https://homepages.cae.wisc.edu/~ece533/images/airplane.png") else { return }
    let data = try! Data(contentsOf: url)
    let image = UIImage(data: data)!
    let resized = resizeImage(image: image, targetSize: CGSize(width: 20, height: 20))?.withRenderingMode(.alwaysOriginal)
    tabBar.items![0].image = resized
    tabBar.items![1].image = resized
}

func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage? {
    let size = image.size
    let widthRatio  = targetSize.width  / size.width
    let heightRatio = targetSize.height / size.height
    var newSize: CGSize
    if(widthRatio > heightRatio) {
        newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
    } else {
        newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
    }
    let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    image.draw(in: rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
}

希望对你有帮助

关于ios - 从服务器加载图像到标签栏项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57289993/

相关文章:

iphone - 发送到实例 0x6d79ed0 的无法识别的选择器

objective-c - 设置相对于设备尺寸的自动布局约束

ios - 为什么我们需要 2 个 .mobileprovision 文件 1 带有 .ipa 以及 1 在设备上?

ios - 如何在 iOS 的 cocoapod 库中使用图像 Assets 目录

ios - 在 Swift 中捕获 NSJSONSerialization 错误

ios - 以编程方式添加 subview 后自动调整单元格大小

ios - 表格 View 未正确适应键盘

ios - 如何在 swift 中使用委托(delegate)通知 UIViewController 在 xib 文件中单击了一个按钮?

swift SpriteKit : TouchesMoved doesn't update when finger stops and camera

ios - Xcode 8 Playground 实时取景不起作用