How do you load custom UITableViewCells from Xib files?

前端 未结 23 1992
抹茶落季
抹茶落季 2020-11-22 11:11

The question is simple: How do you load custom UITableViewCell from Xib files? Doing so allows you to use Interface Builder to design your cells. The answer app

23条回答
  •  Happy的楠姐
    2020-11-22 11:44

    This extension requires Xcode7 beta6

    extension NSBundle {
        enum LoadViewError: ErrorType {
            case ExpectedXibToExistButGotNil
            case ExpectedXibToContainJustOneButGotDifferentNumberOfObjects
            case XibReturnedWrongType
        }
    
        func loadView(name: String) throws -> T {
            let topLevelObjects: [AnyObject]! = loadNibNamed(name, owner: self, options: nil)
            if topLevelObjects == nil {
                throw LoadViewError.ExpectedXibToExistButGotNil
            }
            if topLevelObjects.count != 1 {
                throw LoadViewError.ExpectedXibToContainJustOneButGotDifferentNumberOfObjects
            }
            let firstObject: AnyObject! = topLevelObjects.first
            guard let result = firstObject as? T else {
                throw LoadViewError.XibReturnedWrongType
            }
            return result
        }
    }
    

    Create an Xib file that contains just 1 custom UITableViewCell.

    Load it.

    let cell: BacteriaCell = try NSBundle.mainBundle().loadView("BacteriaCell")
    

提交回复
热议问题