Sam*_*gNY 3 uibutton ios uicollectionview uicollectionviewcell uialertcontroller
我的UICollectionViewCell.swift中有一个按钮:我希望,根据某些参数,它能够呈现警报.
class CollectionViewCell: UICollectionViewCell {
var collectionView: CollectionView!
@IBAction func buttonPressed(sender: UIButton) {
doThisOrThat()
}
func doThisOrThat() {
if x == .NotDetermined {
y.doSomething()
} else if x == .Denied || x == .Restricted {
showAlert("Error", theMessage: "there's an error here")
return
}
}
func showAlert(title: String, theMessage: String) {
let alert = UIAlertController(title: title, message: theMessage, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.collectionView!.presentViewController(alert, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)
在self.collectionView!.presentViewController行我拿到一个破发:
fatal error: unexpectedly found nil while unwrapping an Optional value
我猜这与CollectionView使用方式有关 - 我还没有完全理解选项.我知道一个UICollectionCell不能.presentViewController- 这就是我试图UICOllectionView去做的原因.
我该如何工作?我曾想过使用extension但不知道如何UICOllectionViewCell采用.presentViewController
有任何想法吗?
集合视图单元不应依赖于其父视图或视图控制器的知识,以便维护作为适当的应用程序体系结构一部分的职责的功能分离.
因此,为了使小区采用显示警报的行为,可以使用委托模式.这是通过向具有集合视图的视图控制器添加协议来完成的.
@protocol CollectionViewCellDelegate: class {
func showAlert()
}
Run Code Online (Sandbox Code Playgroud)
并使视图控制器符合该协议:
class MyViewController: UIViewController, CollectionViewCellDelegate {
Run Code Online (Sandbox Code Playgroud)
还要向单元格添加委托属性:
weak var delegate: CollectionViewCellDelegate?
Run Code Online (Sandbox Code Playgroud)
showAlert()在集合视图控制器中移动该函数.
创建单元格时,将单元格的委托指定给集合视图控制器.
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// Other cell code here.
cell.delegate = self
Run Code Online (Sandbox Code Playgroud)
当需要显示警报时,请进行单元格调用
delegate.showAlert()
Run Code Online (Sandbox Code Playgroud)
然后,警报将显示在集合视图控制器上,因为它已被设置为集合视图单元的委托.
| 归档时间: |
|
| 查看次数: |
2794 次 |
| 最近记录: |