ios - 将 block 形式的 objective-c 解决为 swift 3

标签 ios objective-c swift closures objective-c-blocks

我在 block 上遇到了麻烦,在 objective-c 上它运行良好,但我无法转换为 swift 3,

在 objective-c 中

typedef void (^PanCellToDeleteBlock)(NSIndexPath *cellIndexPath);

@interface MyCollectionViewCell : UICollectionViewCell<UIGestureRecognizerDelegate>

@property (copy , nonatomic) PanCellToDeleteBlock panCellToDeleteBlock;

在 swift 3 情况下

public typealias PanCellToDeleteBlock = (_ cell:NSIndexPath) -> Void

class MyCollectionViewCell: UICollectionViewCell,UIGestureRecognizerDelegate {

let panCellToDeleteBlock:PanCellToDeleteBlock? = nil

看起来不快......

这是我在同一个类(class)使用它的时候

在 objective-c 中

if (_panCellToDeleteBlock) {
    _panCellToDeleteBlock(_cellIndexPath);
}

在快速的情况下,一切看起来都是错误的

if (self.panCellToDeleteBlock != nil) {
    self.panCellToDeleteBlock(self.cellIndexPath)
}

这是必须疯狂的部分,这是在 viweController OC案例

cell.panCellToDeleteBlock = ^(NSIndexPath *cellIndexPath){
    [weakSelf.dataArray removeObjectAtIndex:cellIndexPath.row];
    [weakSelf.collectionView reloadData];
};

swift 部分我已经无能为力了....

最佳答案

Swift 3 的等价物是

public typealias PanCellToDeleteBlock = (IndexPath) -> Void

class MyCollectionViewCell: UICollectionViewCell,UIGestureRecognizerDelegate {

var panCellToDeleteBlock : PanCellToDeleteBlock?

self.panCellToDeleteBlock?(self.cellIndexPath)

cell.panCellToDeleteBlock = { [weak self] indexPath in
    self?.dataArray.remove(at: indexPath.row)
    self?.collectionView.reloadData()
}

关于ios - 将 block 形式的 objective-c 解决为 swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44993039/

相关文章:

ios - UISearch 布局在不同 iPhone 上有所不同

ios - 如何在不指定年月日的情况下将 DateComponents 对象转换为本地化字符串,例如 "08:40 PM"?

ios - 更改Sinch短信验证文本

ios - 为什么 UITableViewCell 相互重叠?

ios - 将 Swift 转换为 Objective-C

objective-c - 目标/C : Sorting an array on a custom order

ios - 我们可以在 WKImageView 中使用 GIF 吗?

ios - UIActionSheet奇怪的动画?

ios - 如何将 UIPopoverPresentationController 的高度设置为与 UITableView 相同

ios - NSNumberFormatter 0.1 问题