【问题标题】:Swift 3 Image Slider with button can't change imageview带有按钮的 Swift 3 图像滑块无法更改图像视图
【发布时间】:2017-09-29 19:21:33
【问题描述】:

有图像滑块。我制作了一个图像滑块,每个都是按钮。我还更改了按钮的图像,现在我无法单击图像滑块中的按钮来更改 UIImageView“imgtoy”。我想单击按钮,然后 UIImageView 将更改为我的 choosetoy 数组中的每张照片。任何人都可以帮助我吗?这是我的代码:

@IBOutlet weak var imgtoy: UIImageView!


var itemImage: Int = 2
var imageName: String = ""
var imgBackground = [UIImage(named: "btnballicon.png"), UIImage(named: "btneastfin.png"), UIImage(named: "btnmarblefin.png"), UIImage(named: "btnplanefin.png"), UIImage(named: "btntoyfin.png")]

private let choosetoy = ["ballfin.png", "eastfin.png", "marblefin.png", "planefin.png", "toyfin.png"]

override func viewDidLoad() {
    super.viewDidLoad()


    imageName = choosetoy[itemImage]
    self.imgtoy.image = UIImage(named: imageName)
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return imgBackground.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "foodCollectionViewCell", for: indexPath) as! foodCollectionViewCell


    cell.imgfood.setImage(imgBackground[indexPath.row],for: UIControlState.normal)


    itemImage = indexPath.row

    return cell
}

@IBAction func choosetoy(_ sender: Any) {
    if itemImage != nil {
        imageName = choosetoy[itemImage]
        self.imgtoy.image = UIImage(named: imageName)

    }
}

【问题讨论】:

  • 让你在按钮操作中重新加载数据
  • @ShabbirAhmad 什么是 reloadData。我是swift3的初学者
  • 如果你想改变你的集合或表格数据,那么你必须在按钮方法中重新加载数据。比如'CollectionViewObj.reloadData()'。
  • @HappyChan reloadData 不是 Swift 的一部分,它是 UITableView 的一部分。
  • 但它也可以在collectionView上工作..developer.apple.com/reference/uikit/uicollectionview/…

标签: swift xcode image button swift3


【解决方案1】:

更新代码如下,

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "foodCollectionViewCell", for: indexPath) as! foodCollectionViewCell


    cell.imgfood.setImage(imgBackground[indexPath.row],for: UIControlState.normal)


    cell.imgfood.tag = indexPath.row

    return cell
}

@IBAction func choosetoy(_ sender: UIButton) {
        imageName = choosetoy[sender.tag]
        self.imgtoy.image = UIImage(named: imageName)
}

【讨论】:

  • 它的工作。所以我想知道什么是.tag?为什么tag可以得到我点击图片的数字?
猜你喜欢
  • 2015-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多