【问题标题】:Swift - Add tableview to a UIViewControllerSwift - 将 tableview 添加到 UIViewController
【发布时间】:2017-01-04 20:31:52
【问题描述】:

我正在快速构建一个 iOS 应用程序。我有一个 UIViewController 显示一些标签和字段,我想添加一个表格视图。我是一个完全快速的菜鸟,但经过大量的谷歌搜索,我已经将所有内容集成并“正常工作”。但是,当我使用 dequeueReusableCellWithIdentifier 时,我遇到了“致命错误:在展开可选值时意外发现 nil”。我的单元格是一个自定义类,只有两个 IBOutlets,detailKey 和 detailValue。有什么建议吗?

import UIKit

class ContactViewController: UIViewController, UITableViewDataSource,     UITableViewDelegate {

// MARK:Properties
var contact : Contact?
var params : [Detail]?

@IBOutlet weak var keywords: UILabel!
@IBOutlet weak var name: UILabel!
@IBOutlet weak var contactDetails: UITableView!

// for use in params array
struct Detail {
    var key : String,
        value : String
}

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    contactDetails.dataSource = self
    contactDetails.delegate = self

    if (self.contact != nil) {
        // set default value for params array since optional
        self.params = []

        // make keywords string
        var count : Int = 0
        var keywordString : String = ""

        while count < contact!.keywords.count {
            keywordString += contact!.keywords[count].description

            if count + 1 < contact!.keywords.count {
                keywordString += ", "
            }

            count += 1
        }

        // compile details for tableview
        if (!self.contact!.company.isEmpty) { self.params! += [Detail(key: "Company", value: self.contact!.company)] } // company
        if (!self.contact!.phone1.isEmpty) {
            self.params! += [Detail(key: self.contact!.phone_label1.isEmpty ? "Phone 1" : self.contact!.phone_label1, value: self.contact!.phone1)]
        }
        if (!self.contact!.phone2.isEmpty) {
            self.params! += [Detail(key: self.contact!.phone_label2.isEmpty ? "Phone 2" : self.contact!.phone_label2, value: self.contact!.phone2)]
        }
        if (!self.contact!.email1.isEmpty) {
            self.params! += [Detail(key: self.contact!.email_label1.isEmpty ? "Email 1" : self.contact!.email_label1, value: self.contact!.email1)]
        }
        if (!self.contact!.email2.isEmpty) {
            self.params! += [Detail(key: self.contact!.email_label2.isEmpty ? self.contact!.email_label2 : "Email 2", value: self.contact!.email2)]
        }
        if (!self.contact!.street.isEmpty) { self.params! += [Detail(key: "Address", value: self.contact!.address)] } // address (condition checks for street)
        if (!self.contact!.dob.isEmpty) { self.params! += [Detail(key: "Birthday", value: self.contact!.dob)] } // dob
        if (!self.contact!.social.isEmpty) { self.params! += [Detail(key: "Social Security Number", value: self.contact!.social)] } // social

        self.name.text = contact!.name
        self.keywords.text = keywordString
    }
}

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

// table view stuffs
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.params!.count ?? 0
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    print("going")
    let cell = tableView.dequeueReusableCellWithIdentifier("contactDetail") as! ContactDetailTableViewCell
    let param = self.params![indexPath.row]

    print(param.key + ": " + param.value)

    cell.detailKey.text = param.key
    cell.detailValue.text = param.value

    return cell
}

【问题讨论】:

  • 确保您的Reuse Cell Identifier 正确。也尝试将 tableview 替换为 contactDetails
  • @Dravidian 感谢您的回复!据我所知,我的 Reuse Cell Identifier 是正确的,随附的屏幕截图证明了我的想法。代替 tableview,我尝试了 contactDetails 和 self.contactDetails 都无济于事
  • 您确定您的 IBOutlets 连接正确吗?
  • @penatheboss 感谢您的回复,我刚刚删除并重新连接了所有 IBOutlets,但仍然出现错误。我今天重做了两次表格/单元格类,我无法摆脱它
  • 所有截图证明你的单元格是自定义类 ContactDetailTableViewCell..

标签: ios swift xcode uitableview uiviewcontroller


【解决方案1】:

设置您的单元格标识符选择您的单元格,然后您将在Attributes Inspector 中看到 Identifier 字段,在此处设置您的重用标识符......就是这样......

也尝试添加:-

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

替换

 let cell = tableView.dequeueReusableCellWithIdentifier("contactDetail") as! ContactDetailTableViewCell

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

解释

CMD+CLICK 函数名称:dequeueReusableCellWithIdentifier-- 您将被引导至其文档..

public func dequeueReusableCellWithIdentifier(identifier: String) -> UITableViewCell? // Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one.
@available(iOS 6.0, *)
public func dequeueReusableCellWithIdentifier(identifier: String, forIndexPath indexPath: NSIndexPath) -> UITableViewCell // newer dequeue method guarantees a cell is returned and resized properly, assuming identifier is registered
  • dequeueReusableCellWithIdentifier(identifier: String, forIndexPath indexPath: NSIndexPath) 保证给你一个牢房..

也许这些链接会有所帮助:-

Fatal error: unexpectedly found nil while unwrapping an Optional values

https://stackoverflow.com/a/25569704/6297658

【讨论】:

  • 所以我添加了 numberOfSections 函数,什么也没发生。但是,当我更改 dequeueReusableCellWithIdentifier 函数时,错误会发生变化:由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无法使具有标识符contactDetail的单元格出列-必须为标识符注册一个笔尖或一个类或将原型单元格连接到故事板'
  • 你,先生,很漂亮。我是个白痴。我在身份检查器中设置了标识符,但没有在属性检查器中设置。为此拉了 2 天的头发……谢谢!
【解决方案2】:

确保您的IBOutlets 已正确连接。从您的视图拖动到代码中的连接。

【讨论】:

  • 我已经这样做了,但我仍然收到错误消息。我在 Interface Builder 中构建了布局,并将 tableview 以及名称标签和关键字标签拖到我的视图控制器中。
  • 有时连接断开...插座左侧应该有圆圈。如果它们为空,则表示连接已断开。如果是,请重新连接
  • 谢谢!实际上,我最终用德拉威人的回答来解决它。
猜你喜欢
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 2015-04-15
  • 1970-01-01
  • 1970-01-01
  • 2020-04-07
  • 2023-03-28
  • 2019-06-11
相关资源
最近更新 更多