iOS 使用 Swift 文件作为第一视图

Posted

技术标签:

【中文标题】iOS 使用 Swift 文件作为第一视图【英文标题】:iOS use Swift files as first view 【发布时间】:2014-12-20 17:59:49 【问题描述】:

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

下面的文件是一个表格视图,因为我更喜欢使用 swift 而不是 IB(太多的视图让 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()

【问题讨论】:

"使用 swift 作为用户打开我的应用程序时将看到的第一个视图" 不确定您要说什么...但是当您运行当前代码时会发生什么?跨度> 我的意思是“使用 .swift 文件” 为什么不能使用基于代码的视图控制器作为您的第一个应用程序视图?不管是 Swift 还是 Objective-C。我不会在我的任何应用程序中全部使用 IB。所以是的,这是可能的。 如何在 Xcode 6 中指定这个? 您的操作方式与在 Xcode 5 中相同。在 application:didFinishLaunchingWithOptions: 中实例化您的控制器,并将其设置为窗口的 rootViewController。 【参考方案1】:

根据Apple's View Controller Programming Guide,“当直接使用视图控制器时,您必须编写实例化视图控制器、配置它并显示它的代码。”然而,它也声明“你没有获得故事板的任何好处,这意味着你必须实现额外的代码来配置和显示新的视图控制器。”话虽如此,如果您仍然希望这样做,这就是您的做法(在您的应用委托中):

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 文件作为第一视图的主要内容,如果未能解决你的问题,请参考以下文章

在 iOS 中使用 Swift 保存 PDF 文件并显示它们

如何使用动态视图 iOS Swift 处理导航?

【iOS】UIButton超出父视图点击无效(swift)

IOS - Swift - 向 BarButtonItem 的 customView 添加目标和操作

IOS Swift 中的曲线视图

使用 Appdelegate 在 IOS Swift 中为所有视图控制器创建 Firebase CRUD 方法