如何使用swift以编程方式在选择器视图中为图像设置占位符

时间:2019-05-21 04:46:25

标签: swift

我有一个pickerview,其中显示了图像。我从缓存中选择图像,因此需要一些时间。我想在不从缓存中加载图像时将本地图像显示为占位符图像。当从缓存中加载图像时,它将显示该图像。我是ios开发的新手,所以我不确定如何在选择器视图中将图像显示为占位符。请告诉我是否有任何想法。

我尝试在viewForRow函数中设置图像,然后再从缓存中获取图像。但这不起作用。

myImageView.image = UIImage(named:"no-image")
myImageView = UIImageView(image : UIImage(named: "imagename"))

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    let carrier = self.carriers.object(at: row) as! NSDictionary
    vehicleName = carrier.value(forKey: kcarrierName) as! String
    vehicleID = carrier.value(forKey: kId) as! Int
    self.vehicleType.text = vehicleName
    self.currentVehicle.text = vehicleName
    self.truckType = self.vehicleType.text!
    self.truckType = self.currentVehicle.text!
}

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    let carrier = self.carriers.object(at: row) as! NSDictionary
    vehicleImage = carrier.value(forKey: kImage) as! String
    let viewForImage = UIView()
    var myImageView = UIImageView()
    self.rotAngle = 90 * (.pi/180)
    myImageView.frame = CGRect(x : 0, y : 0, width: 90, height: 90)
    myImageView.cacheImage(urlString: vehicleImage)
    myImageView.transform = CGAffineTransform(rotationAngle: self.rotAngle)
    return myImageView
}

我希望在选择器视图中显示的所有图像都使用占位符图像

2 个答案:

答案 0 :(得分:0)

首先分配默认图像。然后从缓存中获取图像。从服务器上下载图像或从缓存中获取图像之前,将显示默认的本地图像

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    let carrier = self.carriers.object(at: row) as! NSDictionary
    vehicleImage = carrier.value(forKey: kImage) as! String
    let viewForImage = UIView()
    var myImageView = UIImageView()
    self.rotAngle = 90 * (.pi/180)
    myImageView.frame = CGRect(x : 0, y : 0, width: 90, height: 90)
    myImageView.image = UIImage(named:"no-image")
    myImageView.cacheImage(urlString: vehicleImage)
    myImageView.transform = CGAffineTransform(rotationAngle: self.rotAngle)
    return myImageView
}

答案 1 :(得分:0)

我使用过Kingfisher,它可以缓存并进行许多调整和开发选项, 要将占位符设置为imageView,在Kingfisher中非常简单,只需导入Kingfisher并编写以下代码即可。

//placeholder image
let image = UIImage(named: "default_profile_icon")
//imageview to set image via url
imageView.kf.setImage(with: url, placeholder: image)