面对Swift的UIScrollview中的问题

时间:2014-10-14 13:31:44

标签: ios swift uiscrollview ios8

我是ios开发的新手。我正在开发Swift编程。我正在尝试创建一个scrollview但是

"fatal error: unexpectedly found nil while unwrapping an Optional value"

每一次。我在下面的代码中也使用了可选值。

这是我的代码

   class ViewController: UIViewController
    {
     var imagelist=["apple.jpeg","pears.jpeg","banana.jpeg","grapes.jpeg","mango.jpeg"]
     var itemNames = ["Apple", "Pear", "Banana", "Grapes", "Mango"]

    var scrollView: UIScrollView!
    var yPos: Float?
    yPos!=0

    override func viewDidLoad()
    {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        createScrollview()
    }

    func createScrollview()
    {

        scrollView = UIScrollView(frame: view.bounds)

        for var index = 0; index < self.imagelist.count; ++index
        {
            var fruitsImgView:UIImageView!
            fruitsImgView.frame=CGRectMake(0,CGFloat(yPos!), 320, 200)
            fruitsImgView.image=UIImage(named: self.imagelist[index])
            scrollView.addSubview(fruitsImgView)
             yPos!=yPos!+200
        }

        scrollView.contentSize = CGSizeMake(scrollView.frame.size.width  * CGFloat(imagelist.count), scrollView.frame.size.height)

        view.addSubview(scrollView)

    }

    }

我无法解决问题。如果有人在处理,请帮助我。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

第二行是对nil变量的赋值。

var yPos: Float?
yPos!=0 // yPos is nil! 

将其替换为:

var yPos = 0 : Float?

答案 1 :(得分:0)

您没有初始化fruitsImgView。它是一个可选的,它总是自动解包到它的包含类型。当它包含nil(无)时,你无法在Swift中打开Optional。

在使用之前直接初始化fruitsImgView:

let fruitsImageView = UIImageView(image:UIImage(named: self.imagelist[index]))

请注意, UIImageView.init(image:)不会返回可选项。

使用图像初始化图像时,也不需要在图像视图上设置框架 - 初始化后,框架将设置为图像的大小。

yPos 也是如此,只需将其初始化为非可选项:

var yPos:Float = 0.0