gpt4 book ai didi

ios - 如何在 Swift 中将 UIViewController 添加到 UIScrollView

转载 作者:行者123 更新时间:2023-11-28 09:13:23 25 4
gpt4 key购买 nike

我想要一个由 UIViewController 组成的 UIScrollView。我测试了 ScrollView 并且它工作正常,除非我尝试添加 ViewControllers。该项目构建良好,但我收到一个“ fatal error :在展开可选值时意外发现 nil”错误,该错误指向 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.

}}

最佳答案

修复方法是通过 instantiateViewControllerWithIdentifier 从 Storyboard创建 PostViewController,这样,当它的 View 添加到 ScrollView 时,它将从 Storyboard加载一个 imageView。

关于ios - 如何在 Swift 中将 UIViewController 添加到 UIScrollView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28517217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com