作者:Natasha The Robot,原文链接,原文日期:2016-01-14
译者:saitjr;校对:千叶知风;定稿:Cee
使用 Swift 过程中,我意识到的第一个问题就是没有 NsstringFromClass
的替代方案。在自定义 TableViewCell
时,我喜欢用类名作为 cell 的 identifier,然后在重用队列中,通过 NsstringFromClass
来获得 identifier,从而避免拼写错误。
然而,在 Swift 中,我不得不写一个丑陋的 extension 来达到这一目的。(参考 StackOverflow 的回答)
public extension NSObject{ public class var nameOfClass: String{ return NsstringFromClass(self).componentsSeparatedByString(".").last! } public var nameOfClass: String{ return NsstringFromClass(self.dynamicType).componentsSeparatedByString(".").last! } }
不知道以下写法是什么时候出现的,但我确实在 @aligatr 发表的文章中看到了:
// This Now works!!! String(MyTableViewCell)
为确保这个方案可行,我在自己的工程中试了试,没想到真的成功了!!
// BlueTableViewController override func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // 从重用队列中取出 cell!!! let cell = tableView.dequeueReusableCellWithIdentifier(String(BlueTableViewCell),forIndexPath: indexPath) return cell }
超级赞赞赞,我终于可以删掉丑陋的 extension 了。
本文由 SwiftGG 翻译组翻译,已经获得作者翻译授权,最新文章请访问 http://swift.gg。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。