简体   繁体   中英

Instantiating UIView from xib/nib using Swift

I get an error Ambiguous reference to member 'TimelineSectionHeaderView' when I try to call this function like:

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

What am I doing wrong here?

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
  }
}

You need to remove this line below:-

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

Create an instance method like this:-

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

Now inside your ViewController you might have created the outlet of TimelineSectionHeaderView use that outlet variable and then invoke it like this:-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM