如何像 Swift 中的数组一样访问图像资源
How to access Image Assets like an array in Swift
在我的应用程序中,我允许用户根据颜色更改某些 UI 元素。因此,我有一个可用于按钮的图像的三个版本,我想以编程方式 select 图像:
PSEUDO CODE
"image0", "image1", "image3"
var userChoice:integer
myButton.setImage("myImage"+userChoice , .normal)
我在 SO 中看到了这个解决方案:
Programmatically access image assets
Swift 等效代码是什么?
现在我正在使用图片文字:
self.But_Settings.setImage(#imageLiteral(resourceName: "settingswhite"), for: UIControlState.normal)
当然 Xcode 将这部分“#imageLiteral(resourceName: "settingswhite")”更改为无法编辑的图标。
那就不要使用图像字面量。图像文字就是这样 - 代码中的硬值,您在 运行 时间内无法更改。从您的包中动态加载图像:
if let image = UIImage(named: "myImage" + userChoice) {
self.But_Settings.setImage(image, for: .normal)
}
您认为这会有帮助吗? : But_Settings.setImage(UIImage(named: "play.png"), for: UIControlState.normal).这里你使用的是资产名称
由于选择的数量有限,因此听起来像是枚举的好地方。
enum ImageChoice: Int {
case zero = 0, one, two
var image: UIImage {
switch self {
case .zero:
return // Some Image, can use the icon image xcode provides now
case .one:
return //another image
case .two:
return //another image
}
}
}
然后您可以通过使用 Int 值初始化枚举来轻松获得正确的图像。
guard let userChoice = ImageChoice(rawValue: someInt) else { return //Default Image }
let image = userChoice.image
在我的应用程序中,我允许用户根据颜色更改某些 UI 元素。因此,我有一个可用于按钮的图像的三个版本,我想以编程方式 select 图像:
PSEUDO CODE
"image0", "image1", "image3"
var userChoice:integer
myButton.setImage("myImage"+userChoice , .normal)
我在 SO 中看到了这个解决方案: Programmatically access image assets
Swift 等效代码是什么?
现在我正在使用图片文字:
self.But_Settings.setImage(#imageLiteral(resourceName: "settingswhite"), for: UIControlState.normal)
当然 Xcode 将这部分“#imageLiteral(resourceName: "settingswhite")”更改为无法编辑的图标。
那就不要使用图像字面量。图像文字就是这样 - 代码中的硬值,您在 运行 时间内无法更改。从您的包中动态加载图像:
if let image = UIImage(named: "myImage" + userChoice) {
self.But_Settings.setImage(image, for: .normal)
}
您认为这会有帮助吗? : But_Settings.setImage(UIImage(named: "play.png"), for: UIControlState.normal).这里你使用的是资产名称
由于选择的数量有限,因此听起来像是枚举的好地方。
enum ImageChoice: Int {
case zero = 0, one, two
var image: UIImage {
switch self {
case .zero:
return // Some Image, can use the icon image xcode provides now
case .one:
return //another image
case .two:
return //another image
}
}
}
然后您可以通过使用 Int 值初始化枚举来轻松获得正确的图像。
guard let userChoice = ImageChoice(rawValue: someInt) else { return //Default Image }
let image = userChoice.image