Zoe
Zoe

Reputation: 121

solve block form objective-c to swift 3

I have a trouble problem on block, on objective-c it works well, but I couldn't translate to swift 3,

in objective-c case

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

@interface MyCollectionViewCell : UICollectionViewCell<UIGestureRecognizerDelegate>

@property (copy , nonatomic) PanCellToDeleteBlock panCellToDeleteBlock;

in swift 3 case

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

class MyCollectionViewCell: UICollectionViewCell,UIGestureRecognizerDelegate {

let panCellToDeleteBlock:PanCellToDeleteBlock? = nil

it looks no swift.....

here is when I use it in same class

in objective-c case

if (_panCellToDeleteBlock) {
    _panCellToDeleteBlock(_cellIndexPath);
}

in swift case, everything looks wrong

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

here is must crazy part, this is in viweController OC case

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

swift part I already can't do anything ....

Upvotes: 1

Views: 52

Answers (2)

vadian
vadian

Reputation: 285059

The Swift 3 equivalents are

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()
}

Upvotes: 1

Lawliet
Lawliet

Reputation: 3499

Have you tried this

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

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

Upvotes: 0

Related Questions