简体   繁体   English

快速在UITableViewCell内以编程方式添加UIViewController或UIView

[英]Swift Add UIViewController or UIView inside UITableViewCell programatically

I have a custom subclass of a UIViewController created with the swift file and the Xib. 我有一个使用swift文件和Xib创建的UIViewController的自定义子类。

I want to reuse this subclass in multiple places (because is complex), so i don't want to make an other subclass of UITableViewCell or UICollectionViewCell and implement the same behaviour. 我想在多个地方重用此子类(因为很复杂),所以我不想制作UITableViewCell或UICollectionViewCell的另一个子类并实现相同的行为。

My ViewController is also expandable so i don't have a single size but is determined by the visibility of it's components ( i have some constraints that are reduced to 0 when collapsed or to it's normal size when expanded ) 我的ViewController也是可扩展的,所以我没有一个单一的大小,而是由其组件的可见性决定的(我有一些约束,当折叠时会减小为0,而在膨胀时会减小为正常大小)

What's the best way to add this UIViewController (or it's view) to a cell (table or collection ) only by subclassing the cell? 仅通过对单元格进行子类化,将此UIViewController(或其视图)添加到单元格(表或collection)的最佳方法是什么?

Simply by adding the view of the ViewController to contentView ( of a cell) and setting it's frame doesn't work, the view is displayed one on each other and with the origin too upward. 只需将ViewController的视图添加到contentView(单元格的)并设置其框架不起作用,该视图就会彼此显示,并且原点过于向上。

Update: 更新:

Example: 例:

MyViewController: MyViewController:

class MyViewController: UIViewController
{
// has the view property 
}

MyCell 了myCell

class MyCell: UITableViewCell 
{

var myViewController:  MyViewController!
   override func awakeFromNib()
  {
      myViewController = MyViewController()
       self.contentView.addSubview(myViewController.view)
     //what to do next to fit the myViewController inside contentView, 
     //myViewController.view is bigger , 
     //and make the cell to follow the myViewController.view size

  }

}

You're confusing UIView and UIViewController I think. 我认为您在混淆UIViewUIViewController I would just make your custom UIView 我只是让您自定义UIView

import UIKit

class CustomView: UIView {

    override func draw(_ rect: CGRect) {
        // Drawing code

        // Do complicated stuff in this view...
    }

}

You can attach it to a xib if you want to use StoryBoard but it sounds like you're doing it all in code dynamically. 如果要使用StoryBoard,可以将其附加到xib,但这听起来好像是在动态地完成所有代码。 Then create an instance of this view whenever you need it. 然后在需要时创建此视图的实例。 For example: 例如:

    let cv = CustomView()
    cv.frame = CGRect(x: 100, y: 100, width: 200, height: 200)
    self.view.addSubview(cv)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM