gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:42:00 24 4
gpt4 key购买 nike

我使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com