【背景】
折腾:
期间,需要去用代码,而不用那个nib,去创建一个ViewController。
【折腾过程】
1.搜:
swift create viewcontroller programmatically
参考:
viewcontroller – Presenting a view controller programmatically in swift – Stack Overflow
【总结】
用代码手动,动态地,去实现一个视图类ViewController,基本逻辑是:
- 先是类要继承UIViewController
- 然后初始化的时候,要init父类的designated initializer:
- 然后重写viewDidLoad,去实现自己的视图,要显示的内容
- 最好再去实现,当navigation回去的时候,要关闭窗口,比如实现在:closeWindow
- 最好再去重写didReceiveMemoryWarning,当内存吃紧时,删除一些可以删除的数据和资源,比如不重要的缓存数据。
最后用如下代码去创建ViewController:
import UIKit class MyWalletViewController: UIViewController{ init() { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // add your self view here let tabbgView = UIImageView() tabbgView.frame = CGRectMake(0, 20, CGRectGetWidth(self.view.bounds), 44) tabbgView.image = UIImage(named: "title_bg.png") self.view.addSubview(tabbgView) // add back <- icon to back to previous page let backImage = UIImage(named: "back.png") let backBtn = UIButton() backBtn.frame = CGRectMake(10, 30, 24, 24) backBtn.addTarget(self, action:Selector("backToPrevWindow:"), forControlEvents:UIControlEvents.TouchUpInside) backBtn.setImage(backImage, forState:UIControlState.Normal) backBtn.setImage(backImage, forState: UIControlState.Selected) self.view.addSubview(backBtn) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func backToPrevWindow(button : UIButton) { self.navigationController?.popViewControllerAnimated(true) } }
供参考。
更多解释,详见官网文档:
View Controller Programming Guide for iOS: The Role of View Controllers