在swift中的视图控制器中加载集合视图控制器

时间:2016-07-24 05:01:43

标签: ios swift

我有一个标签视图控制器,其中一个标签是一个视图控制器。当用户使用swift点击图像时,我需要能够在该视图控制器中加载集合视图控制器。 这可以通过编程方式完成吗?我的选项卡视图控制器中有3个选项卡,只需要为其中一个选项卡执行此操作,而不是全部。 到目前为止我做了什么: 添加了一个新的swift文件。 home.swift 添加了这个:

// Only execute the code if there's a navigation controller 
if self.navigationController == nil {
    return
}

// Create a navView to add to the navigation bar
let navView = UIView()

// Create the label
let label = UILabel()
label.text = "Text"
label.sizeToFit()
label.center = navView.center
label.textAlignment = NSTextAlignment.Center

// Create the image view
let image = UIImageView()
image.image = UIImage(named: "Image.png")
// To maintain the image's aspect ratio:
let imageAspect = image.image!.size.width/image.image!.size.height
// Setting the image frame so that it's immediately before the text:
image.frame = CGRect(x: label.frame.origin.x-label.frame.size.height*imageAspect, y: label.frame.origin.y, width: label.frame.size.height*imageAspect, height: label.frame.size.height)
image.contentMode = UIViewContentMode.ScaleAspectFit

// Add both the label and image view to the navView
navView.addSubview(label)
navView.addSubview(image)

// Set the navigation bar's navigation item's titleView to the navView
self.navigationItem.titleView = navView

// Set the navView's frame to fit within the titleView
navView.sizeToFit()

然后我将视图控制器的类更改为EventsController,但它抛出以下异常: 异常' NSInternalInconsistencyException',原因: [UICollectionViewController loadView]实例化视图控制器 标识符来自故事板主页,但没有获得UICollectionView

1 个答案:

答案 0 :(得分:0)

您可以做的是创建一个UICollectionViewController类,它是UIViewController的子类。你可以通过这样做很容易地做到这一点:

class CustomTabBarController: UITabBarController {
    override func viewDidLoad() {
    super.viewDidLoad()
    let homeImage = UIImage(named: "home")
    let mainController = MainCollectionViewController(collectionViewLayout: UICollectionViewFlowLayout())
    let navigationController = UINavigationController(rootViewController: mainController)


    viewControllers = [navigationController]
}

请注意,必须为UICollectionViewController指定布局。

现在你的UICollectionViewController类:

class MainCollectionViewController: UICollectionViewController {
    override func viewDidLoad() {
    super.viewDidLoad()
    // code goes here
    }
}