【问题标题】:Swift Add UIViewController or UIView inside UITableViewCell programaticallySwift 以编程方式在 UITableViewCell 中添加 UIViewController 或 UIView
【发布时间】:2017-07-02 03:24:40
【问题描述】:

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

我想在多个地方重用这个子类(因为很复杂),所以我不想创建 UITableViewCell 或 UICollectionViewCell 的其他子类并实现相同的行为。

我的 ViewController 也是可扩展的,所以我没有单一的大小,而是由它的组件的可见性决定(我有一些约束,在折叠时会减小到 0,或者在展开时会减小到正常大小)

仅通过子类化单元格来将此 UIViewController(或其视图)添加到单元格(表或集合)的最佳方法是什么?

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

更新:

例子:

我的视图控制器:

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

我的细胞

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

  }

}

【问题讨论】:

    标签: ios swift uitableview uiviewcontroller swift3


    【解决方案1】:

    我想你混淆了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)
    

    【讨论】:

    • 嗨 Antoine,你误解了这个问题,视图(或 uiviewcontroller)是与 xib 一起创建的(我用其他组件设计视图,我不直接在上面绘制)。我想在自定义单元格上添加此视图并使该单元格适合我的视图。问题是所有的子视图都超出范围并且相互重叠。
    猜你喜欢
    • 1970-01-01
    • 2019-02-11
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    相关资源
    最近更新 更多