我有兩個視圖控制器,讓我們調用X和Y.X有一個名爲「容器」的UIView。 Y有一個UIButton和UITableView,委託和數據源都設置爲Y.在我初始化X視圖中的Y視圖後,X的容器做了container.addSubView (Y.view)
。顯示按鈕和tableview,但表格視圖根本沒有任何內容。當我添加中斷點時,根本不調用numberOfRowsInSection
和cellForRowAtIndexPath
函數。但是,如果我直接打開Y視圖控制器,表視圖會正確更新。爲什麼會發生?以及如何解決它?謝謝。即使視圖控制器是「子」控制器,如何使用委託和數據源更新UITableView?
編輯:代碼。
class Util: NSObject {
static func getViewControllerID(vcname: String, fromStoryboard storyboardName: String = "Main") -> UIViewController {
return UIStoryboard(name: storyboardName, bundle: nil).instantiateViewControllerWithIdentifier(vcname)
}
}
class X : UIViewController {
var tabs = [UIView]();
var tabIdx = 1;
var views = [UIView]();
@IBOutlet var container : UIView!;
override func viewDidLoad() {
super.viewDidLoad();
for i in 1...4 {
let tab = self.view.viewWithTag(i)!;
tab.backgroundColor = UIColor.clearColor();
tabs.append(tab);
}
views.append(Util.getViewControllerID("Dummy").view);
views.append(Util.getViewControllerID("Dummy").view);
views.append(Util.getViewControllerID("Y").view);
views.append(Util.getViewControllerID("Dummy").view);
changeActiveTab(0);
}
func changeActiveTab (idx : Int) {
tabIdx = idx;
for tab in tabs { tab.backgroundColor = UIColor.clearColor(); }
tabs[idx].backgroundColor = UIColor(hexString: "41C7DB");
for view in views { view.removeFromSuperview(); }
let view = views[idx];
view.frame = container.bounds;
container.addSubview(view);
}
@IBAction func tabTapped (sender: AnyObject) {
let btn = sender as! UIButton;
let idx = btn.tag - 11;
changeActiveTab(idx);
}
}
class Y : UIViewController, UITableViewDelegate, UITableViewDataSource {
var dummyData = [String]();
override func viewDidLoad() {
super.viewDidLoad()
for i in 101...106 {
let btn = self.view.viewWithTag(i)! as! UIButton;
btn.makeViewRoundedRectWithCornerRadius(4);
}
dummyData.append("a");
dummyData.append("b");
dummyData.append("c");
dummyData.append("d");
dummyData.append("e");
dummyData.append("f");
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell")!;
cell.backgroundColor = UIColor.clearColor();
var lbl = [UILabel]();
for i in 1...6 { lbl.append(cell.viewWithTag(i)! as! UILabel); }
for i in 0...5 { lbl[i].text = dummyData[i]; }
return cell;
}
}
顯示別忘了你的編碼 – user3182143
@ user3182143完成。 –