【问题标题】:What is the correct way to display random images on table view cell在表格视图单元格上显示随机图像的正确方法是什么
【发布时间】:2019-08-14 09:14:12
【问题描述】:

我试图在表格视图单元格上显示随机图像,但是当我向下和向上滚动时,图像位置发生了变化。

我刚刚在单元格上添加了图像

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    let imagesArr = ["img1","img2","img3","img4"]

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

extension ViewController: UITableViewDataSource,UITabBarDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let randomNumber = Int.random(in: 0...3)

        let cell = tableView.dequeueReusableCell(withIdentifier: "ImageCell") as! ImageCell
        cell.ImageView.image = UIImage(named: self.imagesArr[randomNumber])

        return cell

    }
}

我希望在向下和向上滚动之前获得图像

【问题讨论】:

  • 所有图片的尺寸都一样吗?
  • 是的,但这没关系。例如,如果第一个单元格上的图像是“img3”,当我向下和向上滚动时,我会看到它现在已更改为“img2”
  • 如果您不希望他们更改随机播放列表并且不要在每次想要获取单元格时随机播放

标签: ios swift


【解决方案1】:

如果您想一劳永逸地设置图像,您可以执行以下操作:

class MyCell: UICollectionViewCell {
    func awakeFromNib() {
        super.awakeFromNib()
        let randomNumber = Int.random(in: 0...3)
        let imagesArr = ["img1","img2","img3","img4"]
        ImageView.image = UIImage(named: imagesArr[randomNumber])
    }
}

【讨论】:

    【解决方案2】:

    如果只有离开页面就应该更改随机图像,则在 viewDidLoad() 中添加随机数

    class ViewController: UIViewController {
    
            @IBOutlet weak var tableView: UITableView!
    
            let imagesArr = ["img1","img2","img3","img4"]
    
            var randomNumber = 0
    
            override func viewDidLoad() {
                super.viewDidLoad()
                randomNumber = Int.random(in: 0...3)
            }
        }
    
        extension ViewController: UITableViewDataSource,UITabBarDelegate {
            func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                return 10
            }
    
            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
                let cell = tableView.dequeueReusableCell(withIdentifier: "ImageCell") as! ImageCell
                cell.ImageView.image = UIImage(named: self.imagesArr[randomNumber])
    
                return cell
    
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-28
      • 1970-01-01
      • 2019-10-20
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多