如何在Swift中将UIViewController添加到UIScrollView

时间:2015-02-14 15:38:59

标签: ios iphone swift uiviewcontroller uiscrollview

我想拥有一个UIVcrollView的UIViewControllers。我测试了ScrollView,它工作正常,除非我尝试添加ViewControllers。该项目建设很好,但我得到了一个" fatal error: unexpectedly found nil while unwrapping an Optional value"指向ViewController的错误,特别是行:

self.imageView.image = UIImage(named: self.image!)

但是,当我检查对象时,我可以看到变量imagetext在ViewController中具有值。我正在使用Xcode 6.3 Beta并构建到iOS8.1目标。

以下是代码:

import UIKit

class ViewController: UIViewController {

//@IBOutlet weak var contentScrollView: UIScrollView!

@IBOutlet var contentScrollView: UIScrollView!

//test to make sure ScrollView functions
//let colors = [UIColor.redColor(),UIColor.blueColor(), UIColor.greenColor(), UIColor.whiteColor(), UIColor.blackColor(), UIColor.yellowColor()]

var frame = CGRectMake(0, 0, 0, 0)

var dataArray = [PostItem]()

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

    var da = PostItem(text: "test 1", pic: "beans.jpg")
    self.dataArray.append(da!)

    da = PostItem(text: "test 2", pic: "coffee.jpg")
    self.dataArray.append(da!)

    da = PostItem(text: "test 3", pic: "coffeeCup.jpg")
    self.dataArray.append(da!)

    for index in 0..<self.dataArray.count{
        self.frame.origin.y = self.contentScrollView.frame.size.height * CGFloat(index)
        self.frame.size = self.contentScrollView.frame.size
        self.contentScrollView.pagingEnabled = false
        let tempPost = self.dataArray[index]


        var vc = PostViewController()
        vc.text = tempPost.postText
        vc.image = tempPost.postImage

        self.contentScrollView.addSubview(vc.view)

    }

    self.contentScrollView.contentSize = CGSizeMake(self.view.frame.size.width, CGFloat(self.dataArray.count) * self.contentScrollView.frame.height)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}}

这是我要添加的ViewController的代码:

import UIKit

class PostViewController: UIViewController {

    //let postItem
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var postToFBButton: UIButton!
    @IBOutlet weak var postToTwitterButton: UIButton!
    @IBOutlet weak var postText: UILabel!

    var image:String?
    var text:String?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.imageView.image = UIImage(named: self.image!)
        self.postText.text = text!
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }}

1 个答案:

答案 0 :(得分:0)

修复是从故事板创建PostViewControllerinstantiateViewControllerWithIdentifier,这样,当它的视图添加到滚动视图时,它将从故事板加载imageView。