带按钮的Swift 3图像滑块无法更改图像视图

时间:2017-05-02 09:58:04

标签: swift xcode image button swift3

有图像滑块。我制作了一个图像滑块,每个都是按钮。我也改变了按钮的图像,现在我无法单击图像滑块中的按钮来更改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)

    }
}

1 个答案:

答案 0 :(得分:0)

更新代码如下,

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)
}