【问题标题】:Uibutton issue in swift 3.0swift 3.0中的uibutton问题
【发布时间】:2024-01-16 05:48:02
【问题描述】:
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = UITableViewCell()

    if isFacility {
        cell = tableView.dequeueReusableCell(withIdentifier: "facilityCell")!
        let gameNameLbl = cell.viewWithTag(100) as! UILabel
        gameNameLbl.text = "Badminton Court"
        let gameImgVw = cell.viewWithTag(101) as! UIImageView
        let bookNowBtn = cell.viewWithTag(102) as! UIButton
        bookNowBtn.backgroundColor = DEFAULTAPPCOLOR
        ConstantFile.makeCornerRoundBtnWithOutBorder(btn: bookNowBtn)
        bookNowBtn.tag = indexPath.row
        bookNowBtn.addTarget(self, action: #selector(bookCort(sender:)), for: .touchUpInside)


        bookNowBtn.setTitle("BOOK NOW", for: .normal)
        if indexPath.row % 2 == 0 {
            gameImgVw.backgroundColor = UIColor.red
        }
        else{
            gameImgVw.backgroundColor = UIColor.darkText
        }
    }
    else{
        cell = tableView.dequeueReusableCell(withIdentifier: "bookingCell")!
        let gameImgVw = cell.viewWithTag(103) as! UIImageView
        let gameNameLbl = cell.viewWithTag(104) as! UILabel
        let gameDateLbl = cell.viewWithTag(105) as! UILabel
        let gametimeLbl = cell.viewWithTag(106) as! UILabel
        ConstantFile.roundImageViewWithOutBorder(image: gameImgVw)
        gameNameLbl.text = "Tennis Court"
        gameDateLbl.text = "22 Dec 2017"
        gametimeLbl.text = "7:00pm - 9:00pm"
    }
    return cell

}

在上面的代码中,它让我在滚动表格时崩溃“致命错误:在展开 uibutton 的可选值时意外发现 nil”(在这一行中 let bookNowBtn = cell.viewWithTag(102) as!UIButton)。

【问题讨论】:

  • 显然它正在展开一个不存在的按钮。我假设您已在代码或情节提要的其他位置的单元格中放置了一个按钮,但我不确定您是如何做到的,因为没有关于它的信息。因此,我建议您使用let btn = cell.viewWithTag(102) as UIButton 解开按钮,如果按钮不存在则插入。
  • 最好创建一个自定义单元格,子类,以便您可以使用属性而不是viewWithTag
  • @Rahul :您使用的是静态单元格还是自定义单元格??

标签: ios swift uibutton


【解决方案1】:

可能是你在故事板中放置了不同的标签值。

【讨论】:

    最近更新 更多