[英]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
}
}
我認為您在混淆UIView
和UIViewController
。 我只是讓您自定義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.