简体   繁体   中英

Swift Add UIViewController or UIView inside UITableViewCell programatically

I have a custom subclass of a UIViewController created with the swift file and the Xib.

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.

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 )

What's the best way to add this UIViewController (or it's view) to a cell (table or collection ) only by subclassing the cell?

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.

Update:

Example:

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

  }

}

You're confusing UIView and UIViewController I think. I would just make your custom 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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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