【问题标题】:Translating Objective-C function call to Swift将 Objective-C 函数调用转换为 Swift
【发布时间】:2015-05-07 04:59:01
【问题描述】:

这就是我目前所拥有的......

func rightButtonItemsInRevealTableViewCell(revealTableViewCell: SWRevealTableViewCell!, handler:((Bool) -> (NSArray))!) {

    var item1: SWCellButtonItem = itemWithTitle("Delete", {
        (var success) in
            println("\(success)")
        }
    });

    item1.backgroundColor = UIColor.redColor();
    item1.tintColor = UIColor.whiteColor();
    item1.width = 75;

    return item1;
}

我发现 this 有点帮助,但我仍然遇到一些错误。

这是原始的 Objective-C 代码...

- (NSArray*)rightButtonItemsInRevealTableViewCell:(SWRevealTableViewCell *)revealTableViewCell {

    SWCellButtonItem *item1 = [SWCellButtonItem itemWithTitle:@"Delete" handler:^(SWCellButtonItem *item, SWRevealTableViewCell *cell)
    {
        NSLog( @"Delete");
    }];

    item1.backgroundColor = [UIColor redColor];
    item1.tintColor = [UIColor whiteColor];
    item1.width = 75;

    return @[item1];
}

这是在标题声明中

+ (instancetype)itemWithTitle:(NSString*)title handler:(BOOL(^)(SWCellButtonItem *item, SWRevealTableViewCell* cell))handler;

以及.m文件中的定义

+ (instancetype)itemWithTitle:(NSString *)title handler:(BOOL(^)(SWCellButtonItem *, SWRevealTableViewCell *))handler 
{
    return [[SWCellButtonItem alloc] initWithTitle:title image:nil handler:handler];
}

【问题讨论】:

  • 没有评论的反对票并没有真正的帮助
  • 我认为在 Swift 中已经没有“instancetype”了。
  • 为什么你的 swift 代码中有一个“处理程序”参数?它甚至不存在于您的 Objective-c 代码中?
  • 嗯,有一个init方法,最后以“^”开头的东西就是一个块。我在这里看到了一些问题,询问如何在 Swift 中翻译块。很好的搜索。
  • @beef,处理程序位于 .h 和 .m 文件中,我认为我需要将其作为调用的一部分。

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


【解决方案1】:
func rightButtonItemsInRevealTableViewCell(revealTableViewCell : UITableViewCell) -> NSArray {

    var item1 : SWCellButtonItem = SWCellButtonItem("Delete", handler: ((item : SWCellButtonItem, cell : SWRevealTableViewCell) -> (Void) in {
            NSLog("delete")
        }))
    item1.backgroundColor = UIColor.redColor()
    item1.tintColor = UIColor.whiteColor()
    item1.width = 75
    return [item1];
}

希望我没有忘记任何事情,试试看吧!

【讨论】:

【解决方案2】:

正确的解决方案是

let item : SWCellButtonItem = SWCellButtonItem(title:"Delete", handler:{(item:SWCellButtonItem!, cell:SWRevealTableViewCell!)->(Bool) in

        println("Delete handler")
        return false
    } )

【讨论】:

  • 您说“正确的解决方案是...”但您没有解释如何为什么它是比accepted answer 更好,这大概是您所说的错误。你能扩展你的答案吗?
  • 上一个答案忘记了标题和处理程序的闭包返回(Bool)而不是(Void),项目和单元格也不是可选的!
  • 啊哈。这现在更有意义了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-15
  • 1970-01-01
相关资源
最近更新 更多