繁体   English   中英

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

[英]Swift Add UIViewController or UIView inside UITableViewCell programatically

我有一个使用swift文件和Xib创建的UIViewController的自定义子类。

我想在多个地方重用此子类(因为很复杂),所以我不想制作UITableViewCell或UICollectionViewCell的另一个子类并实现相同的行为。

我的ViewController也是可扩展的,所以我没有一个单一的大小,而是由其组件的可见性决定的(我有一些约束,当折叠时会减小为0,而在膨胀时会减小为正常大小)

仅通过对单元格进行子类化,将此UIViewController(或其视图)添加到单元格(表或collection)的最佳方法是什么?

只需将ViewController的视图添加到contentView(单元格的)并设置其框架不起作用,该视图就会彼此显示,并且原点过于向上。

更新:

例:

MyViewController:

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

了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

  }

}

我认为您在混淆UIViewUIViewController 我只是让您自定义UIView

import UIKit

class CustomView: UIView {

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

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

}

如果要使用StoryBoard,可以将其附加到xib,但这听起来好像是在动态地完成所有代码。 然后在需要时创建此视图的实例。 例如:

    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