gpt4 book ai didi

ios - 使用带有本地 JSON 数据 Swift 的图像

转载 作者:行者123 更新时间:2023-12-01 19:49:12 27 4
gpt4 key购买 nike

我有一个本地 JSON 数据,它会在应用加载时填充我的 View 。我现在正在尝试加载本地镜像并将它们附加到必要的对象中。

这是我的 JSON 数据:

{
"description": "Birds of Antarctica, grouped by family",
"source": "https://en.wikipedia.org/wiki/List_of_birds_of_Antarctica",
"birds": [
{
"bio": "Albatrosses are highly efficient in the air, using dynamic soaring and slope soaring to cover great distances with little exertion. They feed on squid, fish and krill by either scavenging, surface seizing or diving. Albatrosses are colonial, nesting for the most part on remote oceanic islands, often with several species nesting together.",
"family": "Albatrosses",
"imageURL": "albatross.jpg",
"members": [
"Wandering albatross",
"Grey-headed albatross",
"Black-browed albatross",
"Sooty albatross",
"Light-mantled albatross"
]
},
{
"bio": "Terns and shags are medium-to-large birds, with body weight in the range of 0.35–5 kilograms (0.77–11.02 lb) and wing span of 45–100 centimetres (18–39 in). The majority of species have dark feathers. The bill is long, thin and hooked. Their feet have webbing between all four toes. All species are fish-eaters, catching the prey by diving from the surface.",
"family": "Terns",
"imageURL": "terns.jpg",
"members": [
"Arctic tern",
"Antarctic tern"
]
}
]
}

我可以使用此处提出的建议来获取家人、简历和成员: Correctly parsing through nested JSON using data model for multiple reuse. Swift .

在用于填充我的表的 BirdCell 类中,我有这个:
class BirdCell: UITableViewCell {

var bird: Bird!
var imageUrl: String!
@IBOutlet weak var nameLbl: UILabel!
@IBOutlet weak var birdImage: UIImageView!

override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}

override func prepareForReuse() {
super.prepareForReuse()

birdImage.image = nil
imageUrl = bird.imageUrl?.absoluteString

if let imageUrl = bird.imageUrl {
let resource = ImageResource(downloadURL: imageUrl)
birdImage.kf.setImage(with: resource)

if birdImage.image == nil {

birdImage.image = UIImage(named: "placeholder")
} else {

}
}
nameLbl.text = bird.family

}

我正在使用 翠鸟缓存图像。我收到了 nil尝试通过缓存图像时。

如果我的方法不是我正在尝试的最佳实践,请随时告诉我,并指导我如何实现它。

最佳答案

图像是如何添加到您的项目中的?我猜它们在您的 Images.xcassets 文件中?在这种情况下,只需仔细检查 JSON 中的名称是否与 Assets 文件中的名称匹配。如果文件是本地文件,为什么要尝试创建图像 URL?

你什么时候在你的细胞上设置鸟属性 - 当细胞被重用时,看起来这可能是零?我建议将您的代码从 prepareForReuse() 移出到您自己的方法并从 cellForRowAt: 调用它.就像是:

func updateWithBird(bird: Bird) {
birdImage.image = UIImage(named: bird.image)
nameLbl.text = bird.family
}

关于ios - 使用带有本地 JSON 数据 Swift 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46664847/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com