最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Swift中如何用代码的方式去创建ViewController

Swift crifan 4220浏览 0评论

【背景】

折腾:

【已解决】Swift创建新的页面视图并添加一个列表视图

期间,需要去用代码,而不用那个nib,去创建一个ViewController。

【折腾过程】

1.搜:

swift create viewcontroller programmatically

参考:

viewcontroller – Presenting a view controller programmatically in swift – Stack Overflow

【总结】

用代码手动,动态地,去实现一个视图类ViewController,基本逻辑是:

  1. 先是类要继承UIViewController
  2. 然后初始化的时候,要init父类的designated initializer:
  3. 然后重写viewDidLoad,去实现自己的视图,要显示的内容
  4. 最好再去实现,当navigation回去的时候,要关闭窗口,比如实现在:closeWindow
  5. 最好再去重写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

转载请注明:在路上 » 【已解决】Swift中如何用代码的方式去创建ViewController

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.168 seconds, using 22.18MB memory