【问题标题】:Blank space between tableview and date picker表格视图和日期选择器之间的空格
【发布时间】:2019-06-13 20:49:44
【问题描述】:

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

'线程 1:致命错误:在展开可选值时意外发现 nil'

我认为这是因为我设置了原型单元格:1。所以我将其设为 0,但也没有用。

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视图部分//

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?
  • 查看我的答案,让我知道它是否适合您。

标签: swift uitableview


【解决方案1】:

您的代码正在崩溃,因为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,它告诉您用户选择的行。

【讨论】:

  • 感谢我尝试过,但看起来像 tableview 第一行的空间仍然存在,现在当我单击空间时,它显示“0”。我不知道它来自哪里
  • @mjk 因为你在这里调用了setTitleddn.setTitle("\(indexPath.row)", for: .normal),导致按钮显示“0”。
  • @mjk 要显示日期,请查看this answer。基本上,将标题设置为不是行号,而是日期选择器的实际日期。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-22
  • 2012-03-06
  • 2016-07-03
  • 2019-01-26
  • 2015-07-08
相关资源
最近更新 更多