iOS 使用 Swift 文件作为第一个 View

标签 ios swift

在 Xcode 6 中,是否可以使用 .swift 文件作为用户打开我的应用程序时看到的第一个 View ?

下面的文件用于表格 View ,因为我更喜欢使用 swift 而不是 IB( View 太多会使 IB 看起来很乱)。

    import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var tableView: UITableView!
    let items = ["Hello 1", "Hello 2", "Hello 3"]

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
        self.tableView = UITableView(frame:self.view.frame)
        self.tableView!.dataSource = self
        self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
        self.view.addSubview(self.tableView)

    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return self.items.count;
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
        cell.textLabel.text = "\(self.items[indexPath.row])"
        return cell
    }
}

var ctrl = ViewController()

最佳答案

根据 Apple's View Controller Programming Guide ,“当直接使用 View Controller 时,您必须编写代码来实例化 View Controller 、配置它并显示它。”然而,它也指出“你没有获得 Storyboard的任何好处,这意味着你必须实现额外的代码来配置和显示新的 View Controller 。”话虽这么说,如果您仍然想这样做,这就是您的做法(在您的应用委托(delegate)中):

var window: UIWindow?
var viewController: ViewController?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    window?.backgroundColor = UIColor.whiteColor()

    viewController = ViewController()
    // Any additional setup

    window?.rootViewController = viewController
    window?.makeKeyAndVisible()

    return true
}

关于iOS 使用 Swift 文件作为第一个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27582857/

相关文章:

ios - iOS 应用程序上的一次性密码 - 建议未出现在键盘上方

ios - 为什么 UIView 的边缘对于巨大的圆角半径不平滑?

ios - 如何为 iOS UIButton 对象实现此 UI/UX 设计

ios - 如何在 Alamofire 中禁用缓存

swift - 以编程方式截屏 | swift 3,macOS

objective-c - 对于强集合实例,赋值给nil等于释放赋值给nil吗?

ios - 删除存储在 nsuserdefault 中的 nsdata

ios - 在 IOS 9 中合并音频文件时 AVAssetExportSessionStatusFailed

ios - Swift - 使用 viewDidAppear 中的新信息重新加载 UIPageViewController

ios - 应用关闭时截图