swift - 表格 View 和日期选择器之间的空白

标签 swift uitableview

我使用 Tableview 在按钮单击上创建了显示/隐藏日期选择器,并在按钮上显示日期。 但是当我运行这个时, TableView 和日期选择器内部之间有奇怪的空白。 当我点击这个空间时,出现错误

'Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value'

我认为这是因为我设置了原型(prototype)单元:1。所以我将其设置为0,但也不起作用。

1

var dateFormatter = DateFormatter()
var datePickerIndexPath: NSIndexPath?
var datepicker : UIDatePicker?

@IBOutlet weak var ddn: UIButton!
@IBOutlet weak var TV: UITableView!
override func viewDidLoad() { 
   super.viewDidLoad() 

      TV.isHidden=true

      datepicker = UIDatePicker()
      datepicker? = UIDatePicker.init(frame: CGRect(x:0, y:40, width:252, height:150))
      datepicker?.setValue(UIColor(red:0.95, green:0.92, blue:0.90, alpha:1.0), forKeyPath: "textColor")
      datepicker?.datePickerMode = .date
      datepicker?.addTarget(self, action: #selector(datepickerViewController.dateChanged(datepicker: )),for: .valueChanged)



      TV.addSubview(datepicker!)
}

... 
button click action/animate
...


//talbe View 部分//

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        var rows = 1
        if datePickerIndexPath != nil {rows += 1 }
        return rows
    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "DatePickerCell", for: indexPath)
        cell.textLabel?.text = dateFormatter.string(from: (datepicker?.date)!)

        return cell
    }


    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        ddn.setTitle("\(datePickerIndexPath!.row)", for: .normal)
        //when i click the space, an error occurs in this part//

    }
}


最佳答案

您的代码正在崩溃,因为datePickerIndexPath是一个从未设置的可选值。像这样声明它不会为变量赋予任何值:

var datePickerIndexPath: NSIndexPath?

因此,datePickerIndexPath 的值为 nil。

解决方案是完全删除该变量。然后,更改此代码:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    ddn.setTitle("\(datePickerIndexPath!.row)", for: .normal)

}

对此:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    ddn.setTitle("\(indexPath.row)", for: .normal)

}

didSelectRowAt 方法已经为您提供了 indexPath,它告诉您用户选择的行。

关于swift - 表格 View 和日期选择器之间的空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56588383/

相关文章:

ios - Swift:如何在不添加 segue 的情况下切换回以前的 UITableViewController

swift - 如何在swift中将字符转换为字符串?

ios - 旧 View Controller 未关闭

swift - 将 Swift 数组转换为 NSArray

iphone - viewForHeaderInSection 的框架始终大小相同

objective-c - UITableViewCell 的最大高度是多少?

swift - scrolltoitematindexpath 总是返回到相同的位置

cocoa-touch - 使用 Swift 子类化 SKShapeNode

ios - 为什么使用 xib 和自动布局时 tableviewcell 的 contentView 中有 inset?

iphone - 从 UITableView 创建 UIImage