简短版
在以下代码摘录中,我将cell
(非零变量)的值分配给popOverVC.popoverPresentationController?.sourceView
,在分配后仍为nil
:
guard let cell = sender.superview?.superview as? HoleTableViewCell else {
return
}
print("Cell number " + String(describing: cell) + " selected")
popOverVC.popoverPresentationController?.sourceView = cell
print(String(describing: popOverVC.popoverPresentationController?.sourceView))
两个印刷语句产生以下两行:
Cell number <Eclectic_Boogaloo.HoleTableViewCell: 0x7fde340a3000; baseClass = UITableViewCell; frame = (0 0; 374 69); clipsToBounds = YES; autoresize = W; layer = <CALayer: 0x60400003e140>> selected
nil
为什么第二个print
语句会返回一个nil值?
长版
我有UITableView
名为Holes Table
,其中包含“HoleTableViewCell”类的自定义单元格。在单元格内是一个按钮,选中后,以编程方式调用弹出窗口。该按钮的完整代码如下:
@IBAction func selectParValue(_ sender: UIButton) {
// Retrieve the cell containing the selected button
guard let cell = sender.superview?.superview as? HoleTableViewCell else {
return
}
let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "parPopover")
print("Cell number " + String(describing: cell) + " selected")
popOverVC.popoverPresentationController?.sourceView = cell
print(String(describing: popOverVC.popoverPresentationController?.sourceView))
popOverVC.popoverPresentationController?.sourceRect = cell.bounds
popOverVC.modalPresentationStyle = .popover
popOverVC.popoverPresentationController!.delegate = self
present(popOverVC, animated: true, completion: nil)
}
但是,在运行时,我收到以下错误,因为弹出视图控制器上的sourceView
为nil:
2017-12-31 18:39:27.670140+0000 Eclectic Boogaloo[10333:1091992] *** Terminating app due to uncaught exception 'NSGenericException', reason: 'UIPopoverPresentationController (<UIPopoverPresentationController: 0x7f9ed6552200>) should have a non-nil sourceView or barButtonItem set before the presentation occurs.'
答案 0 :(得分:0)
解决方案只是在modalPresentationStyle
和sourceView
之前设置sourceRect
。
感谢@maddy的提示。
答案 1 :(得分:0)
问题是popoverPresentationController
为nil
,直到您将视图控制器的modalPresentationStyle
设置为.popover
。
因此,您需要移动尝试设置sourceView
和sourceRect
。
let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "parPopover")
popOverVC.modalPresentationStyle = .popover
popOverVC.popoverPresentationController?.sourceView = cell
popOverVC.popoverPresentationController?.sourceRect = cell.bounds
popOverVC.popoverPresentationController?.delegate = self
present(popOverVC, animated: true, completion: nil)