【问题标题】:How to convert a xCode xib based view controller to a storyboard view controller?如何将基于 xCode xib 的视图控制器转换为情节提要视图控制器?
【发布时间】:2016-01-12 15:39:42
【问题描述】:

我正在关注一个使用 xib 文件作为视图控制器的 Swift 教程,并试图将其放入情节提要中。我使用 xCode7 和 Swift 2.1 我在下面的代码中遇到了一些问题:

var cell:CatsTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CatsTableViewCell

        if(cell == nil) {
            cell = NSBundle.mainBundle().loadNibNamed("CatsTableViewCell", owner: self, options: nil)[0] as? CatsTableViewCell
        }

我如何将上面的这个翻译成故事板在项目中使用的那个?

我在下面也遇到了一些问题。我不久前开始使用 xCode,我对下面代码的含义有些困惑。我试过用谷歌搜索它,但我刚刚得到了非常详细的解释,作为初学者很难理解。

required init(coder aDecoder:NSCoder)
    {
        fatalError("NSCoding not supported")  
    }

您可以在下面找到视图控制器的完整代码以及完整教程的链接。希望有人可以帮助我,拜托。提前致谢。

http://www.appcoda.com/instagram-app-parse-swift/

//
//  CatsTableViewController.swift
//  Paws
//
//  Created by Simon Ng on 15/4/15.
//  Copyright (c) 2015 AppCoda. All rights reserved.
//

import UIKit

class CatsTableViewController: PFQueryTableViewController {


    let cellIdentifier:String = "CatCell"

    override func viewDidLoad() {


     tableView.registerNib(UINib(nibName: "CatsTableViewCell", bundle: nil), forCellReuseIdentifier: cellIdentifier)

        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func queryForTable() -> PFQuery {
        let query:PFQuery = PFQuery(className:self.parseClassName!)


        if(objects?.count == 0)
        {
            query.cachePolicy = PFCachePolicy.CacheThenNetwork
        }

        query.orderByAscending("name")

        return query

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {

        var cell:CatsTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CatsTableViewCell

        if(cell == nil) {
            cell = NSBundle.mainBundle().loadNibNamed("CatsTableViewCell", owner: self, options: nil)[0] as? CatsTableViewCell
        }

        cell?.parseObject = object

        if let pfObject = object {
            cell?.catNameLabel?.text = pfObject["name"] as? String

            var votes:Int? = pfObject["votes"] as? Int
            if votes == nil {
                votes = 0
            }
            cell?.catVotesLabel?.text = "\(votes!) votes"

            var credit:String? = pfObject["cc_by"] as? String
            if credit != nil {
                cell?.catCreditLabel?.text = "\(credit!) / CC 2.0"
            }

            cell?.catImageView?.image = nil
            if var urlString:String? = pfObject["url"] as? String {
                var url:NSURL? = NSURL(string: urlString!)

                if var url:NSURL? = NSURL(string: urlString!) {
                    var error:NSError?
                    var request:NSURLRequest = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 5.0)

                    NSOperationQueue.mainQueue().cancelAllOperations()

                    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
                        (response:NSURLResponse?, imageData:NSData?, error:NSError?) -> Void in

                        cell?.catImageView?.image = UIImage(data: imageData!)

                    })
                }
            }

        }

        return cell
    }

    override init(style: UITableViewStyle, className: String!)
    {
        super.init(style: style, className: className)

        self.pullToRefreshEnabled = true
        self.paginationEnabled = false
        self.objectsPerPage = 25

        self.parseClassName = className

        self.tableView.rowHeight = 350
        self.tableView.allowsSelection = false
    }

    required init(coder aDecoder:NSCoder)
    {
        fatalError("NSCoding not supported")  
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

【问题讨论】:

    标签: ios swift swift2 xcode7


    【解决方案1】:

    更改以下代码

     var cell:CatsTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CatsTableViewCell
    
        if(cell == nil) {
            cell = NSBundle.mainBundle().loadNibNamed("CatsTableViewCell", owner: self, options: nil)[0] as? CatsTableViewCell
        }
    

    到

     let cell = tableView.dequeueReusableCellWithIdentifier("CatsTableViewCell", forIndexPath: indexPath) as! CatsTableViewCell
    

    对于“必填”关键字检查链接What does the "required" keyword in Swift mean?

    【讨论】:

    • 另外请注意,一旦您使用情节提要,您将不需要标记为“必需”的 init 方法 - 您应该取出 init 方法,而是使用 viewDidLoad 进行设置。
    • 感谢您的回答!我已将 var "..." 更改为 let ".." 并删除了 init 方法。现在在 viewDidLoad 中有: tableView.registerNib(UINib(nibName: "CatsTableViewCell", bundle: nil), forCellReuseIdentifier: cellIdentifier) 请问如何设置 viewDidLoad? @pbergson
    • 你的 viewController 应该有一个 tableview 的属性,像这样:
    【解决方案2】:

    你的 viewController 应该有一个 tableview 的属性,像这样:

    @IBOutlet var tableview : UITableView?
    

    然后在您的故事板中,将 tableview 连接到该插座(有关连接插座的教程比比皆是,或者如果您遇到困难,请告诉我)。然后,在 viewDidLoad 中,调用与上面相同的方法:self.tableView.registerNib 等。

    【讨论】:

    • 谢谢@pbergson,我已经完成了,但我得到了这个错误:'NSInternalInconsistencyException',原因:'无法使具有标识符 CatsTableViewCell 的单元格出列 - 必须为标识符注册一个 nib 或一个类或连接故事板中的原型单元格......但如果我使用此代码:让 cell = tableView.dequeueReusableCellWithIdentifier("CatsTableViewCell", forIndexPath: indexPath) as! CatsTableViewCell .....应用不会崩溃,但不会在单元格中显示图像。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 2012-07-10
    • 2017-11-14
    • 2012-01-02
    • 2014-08-12
    • 2013-10-21
    • 1970-01-01
    相关资源
    最近更新 更多