使用Switch语句从Xcassets加载imageView

时间:2015-07-09 00:14:46

标签: ios swift uiimageview switch-statement

我在Xcassets中有@ 1 @ 2和@ 3的图像,我正在尝试使用下面的代码将图像加载到滚动视图页面上,该代码由于其年龄而打开图像。页面由位置确定,并在viewWillLoad函数中调用switch语句。图像没有加载,但声音正在工作,所以我知道这是图像加载是问题。你能帮忙吗?

override func viewDidDisappear(animated: Bool) {
    self.imageView.removeFromSuperview()
    self.imageView.image = nil
}



override func viewWillAppear(animated: Bool) {

    showImageView()

    let tapGestureImage = UITapGestureRecognizer(target: self, action: Selector("handleTapGestureImage:"))
    imageView.addGestureRecognizer(tapGestureImage)
    imageView.userInteractionEnabled = true
}




// MARK: BWWalkthroughPage Implementation

func walkthroughDidScroll(position: CGFloat, offset: CGFloat) {

    // getting the page number from the scroll position. First page loads as nil so want it to be zero.

    screenPage  = Int(((position / view.bounds.size.width) + 1) - 1)
}



func showImageView() {

    // change imageView in bundle depending on which scrollview page you are.
    switch screenPage {

    case 0:

        self.imageView.image = UIImage(named: "Aligator", inBundle: NSBundle.mainBundle(), compatibleWithTraitCollection: self.traitCollection)
        self.view.addSubview(imageView)

    case 1:

        self.imageView.image = UIImage(named: "Bear", inBundle: NSBundle.mainBundle(), compatibleWithTraitCollection: self.traitCollection)
        self.view.addSubview(imageView)

    default:
        self.imageView.image = nil
    }
}

1 个答案:

答案 0 :(得分:1)

有些事情对你来说很重要。 您无需一遍又一遍地从视图层次结构中添加/删除图像视图。只需拨打imageView.image = nil即可。

第二件事是你不需要使用完整的方法UIImage(named:inBundle:compatibleWithTraitCollection:)。您应该只需使用UIImage(named:)即可。如果你发现自己不得不使用前者,那么在你职业生涯的这个阶段你可能会得到比你能处理的更多的东西。

第三件事是,当你覆盖一个方法时,你必须在99%的情况下调用super。

这是一个应该有效的例子:

import UIKit

class MyViewController: UIViewController {

    override fun viewDidLoad() {
        super.viewDidLoad()
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("handleTapGestureImage:"))
        imageView.addGestureRecognizer(gestureRecognizer)
        imageView.userInteractionEnabled = true
    }

    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated: animated)
        self.imageView.image = nil
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated: animated)
        showImageView()
    }

    func walkthroughDidScroll(position: CGFloat, offset: CGFloat) {
        screenPage  = Int(((position / view.bounds.size.width) + 1) - 1)
    }

    func showImageView() {
        switch screenPage {
        case 0:
            imageView.image = UIImage(named: "Aligator")
        case 1:
            imageView.image = UIImage(named: "Bear")
        default:
            imageView.image = nil
        }
    }
}