使用Swift从xib / nib实例化UIView

时间:2017-09-06 20:29:20

标签: ios swift cocoa-touch uiview

当我尝试调用此函数时出现错误Ambiguous reference to member 'TimelineSectionHeaderView'

if let view = TimelineSectionHeaderView.instantiateFromNib() {
    return view
}

我在这里做错了什么?

import UIKit

class TimelineSectionHeaderView: UIView {

  @IBOutlet weak var dayLabel: UILabel!
  @IBOutlet weak var dateLabel: UILabel!

  class func instantiateFromNib() -> TimelineSectionHeaderView? {
      let x = UINib(nibName: "timelineSectionHeader", bundle: nil).instantiate(withOwner: nil, options: nil).first as? TimelineSectionHeaderView
      print(x ?? "no value")
      return x
  }
}

1 个答案:

答案 0 :(得分:0)

您需要删除以下这一行: -

if let view = TimelineSectionHeaderView.instantiateFromNib() {
    return view
}

创建一个这样的实例方法: -

func instantiateFromNib() -> TimelineSectionHeaderView? {
      let x = UINib(nibName: "timelineSectionHeader", bundle: nil).instantiate(withOwner: nil, options: nil).first as? TimelineSectionHeaderView
      print(x ?? "no value")
      return x
  }

现在在你的ViewController中你可能已经创建了TimelineSectionHeaderView的出口使用outlet变量,然后像这样调用它: -

if let view = timelineViewInstanceVariable.instantiateFromNib() {
    return view
}