ios - 如何更改具有可变图像名称的按钮的图像?
问题描述
我想以编程方式更改按钮的图像。我现在唯一的方法是:
button.setImage(UIImage.init(named: "imagename", for: .normal))
但现在我想使用一个变量imagename
。有没有办法做到这一点?最后,我有一个图像文件夹,然后我使用函数收集图像。该函数的最后一行是我将 imagename 设置为收集的图像的名称。我知道如何编写这个函数。但我不知道如何使用变量图像名设置按钮的图像。我希望你能理解我的问题,任何人都可以帮助我。
这里的代码:
var imageArroy = [UIImage(named:"car1"),UIImage(named:"car2")]
//scrollview
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageArroy.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCollectionViewCell", for: indexPath) as! ImageCollectionViewCell
var imagename: String = imageArroy[indexPath.row])
cell.car.setImage(UIImage.init(named: imagename)!, for: .normal)
return cell
}
解决方案
由于您有一个元素数组,因此您可以通过指定其索引来获取某个元素
array[index]
^ Int
...请注意,第一个元素的索引是 0,而不是 1
因此,cellForRowAt
您可以UIImage?
通过在索引等于当前索引路径行的数组中获取图像来确定。不要忘记打开它
cell.car.setImage(imageArroy[indexPath.row]!, for: .normal)
推荐阅读
- r - 替换列表中的数字,同时保留 R 中的字母
- javascript - 在悬停时使用 Jquery / Javascript 显示另一个 div
- python - 当我尝试在 Windows 10 上使用 get-pip.py 安装 pip 时出错
- c# - 在查找 1 - X 之间的缺失数字时使用了令人困惑的值
- javascript - 仅 javascript:禁用行和列中的单选按钮
- amazon-web-services - 如果非 root 卷已满,为什么 AWS EC2 ubuntu 机器无法启动?
- flutter - 如何知道我的 Flutter Web 应用程序是在移动设备还是桌面设备上运行
- sql - sql查询下个月的特定日期
- android - appBar 在可见性消失时仍在占用空间
- angular - 如何在 app.module.ts 中导入 HttpClientModule 而不会出现 StaticInjection 错误?