ios - 能够从 Storyboard 和 ViewController 加载 xib

标签 ios swift storyboard

我正在尝试创建完美的解决方案,以直接从代码和 Storyboard 中创建自定义 UIView 子类。但是,我没有找到任何解决方案。

对于通过 Storyboard的 IBDesignable 解决方案,我遵循了此示例 http://supereasyapps.com/blog/2014/12/15/create-an-ibdesignable-uiview-subclass-with-code-from-an-xib-file-in-xcode-6并且工作完美。

但是如果我尝试通过 UIViewController 通过调用此扩展方法来调用此子类:

extension UIView {
    class func loadFromNibNamed(nibNamed: String, bundle : NSBundle? = nil) -> UIView? {
        return UINib(
            nibName: nibNamed,
            bundle: bundle
        ).instantiateWithOwner(nil, options: nil)[0] as? UIView
    }
}

它崩溃并说错过了该类与键的键值编码不兼容

有人找到了可以与我分享的解决方案吗?

我需要它,因为我应该在 Storyboard 中使用这个UIView,并且也将其用作UITableview SectionHeader

最佳答案

为了保留这两种情况,我更愿意将其写在我的子类声明中:

@IBDesignable class CustomView: UIView {

    var view: UIView!

    @IBOutlet weak var button: UIButton!
    @IBOutlet weak var label: UILabel!


    func xibSetup() {
        view = loadViewFromNib()
        view.frame = bounds
        view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
        addSubview(view)
    }

    func loadViewFromNib() -> UIView {

        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: "CustomView", bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView

        return view
    }


    override init(frame: CGRect) {
        super.init(frame: frame)
        xibSetup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        xibSetup()
    } 
}

通过这种方式,我可以看到它并将其添加到我的 Storyboard中。 在 ViewForHeaderInSection 方法中,我这样写:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

let header = UIView()

let view:CustomView = CustomView(frame: CGRect(x: 0, y: 0, width:  self.view.frame.width, height: 30))

view.label.text = "header title: \(section)"

header.addSubview(view)


return header

}

这样就可以了;)

关于ios - 能够从 Storyboard 和 ViewController 加载 xib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39816898/

相关文章:

使用 FirebaseApp.configure() 时 iOS 应用崩溃

ios - 容器 View 和容器 View Controller 有什么区别?

ios - 为什么我的 NSTimer 会双倍递减我的计时器?

ios - 使用 Swift 在 Xcode 6 中使用 xib 在自定义 uiview 中获取 SIGABRT

ios - Collectionview 自定义单元格布局/行为

ios - Xcode IOS 无法识别 CGDataProviderCreateWithCFData 函数

xcode - Storyboard:使用委托(delegate)/协议(protocol)方法关闭 Popover

objective-c - 使用 Storyboard, subview 在关闭时会丢失数据。尝试了解原因并解决

iOS UI 自动化 : toggle network settings during test execution time from within the tests

ios - XCode 7 如何固定到 super View 而不是播放指南