在 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/