Water Magical
Water Magical

Reputation: 1179

create UIView with xib in Swift

I want to create a Custom View with xib, So I did CreateTask.xib that contain a TextField and class is CustomUIView: UIView

I follow this step from http://swiftdeveloperblog.com/creating-custom-user-interface-files-with-xib-in-xcode-6-and-swift/

 
import UIKit

class CreateTaskView: UIView {

@IBOutlet weak var taskNameField: UITextField! var nibView: UIView! var taskName: String? { get { if taskNameField == nil { return "taskNameField is nil" } if let s = taskNameField.text { return s } else { return "" } } } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { print("infinite loop") super.init(coder: aDecoder) setup() } func setup() { nibView = loadViewFromNib() nibView.frame = bounds nibView.autoresizingMask = [UIViewAutoresizing.flexibleWidth ,UIViewAutoresizing.flexibleHeight] addSubview(nibView) } func loadViewFromNib() -> UIView { let nib = UINib(nibName: "CreateTask", bundle: nil) let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView return view }

}

when i instance CreateTaskView, that CreateTaskView was created infinite by loadViewFromNib(), I think it probably the reason is "xib class is CustomUIView", so I take it out.

but i can't get the UITextField outlet in xib now, how can i do?

Upvotes: 1

Views: 5719

Answers (2)

Suhit Patil
Suhit Patil

Reputation: 12023

  1. Go to CreateTask.xib and tap on File's Owner tab
  2. set the owner of the xib by tapping Identity Inspectorand set the custom class as CreateTaskView
  3. then try creating the outlet of textfield to CreateTaskView

Upvotes: 0

NeverHopeless
NeverHopeless

Reputation: 11233

It is not a good idea to create nib from the class itself, instead the class that creates the instance of the customview should load the view with its nib file. An Objective-C example:

CustomView *myView = (CustomView *)[[[NSBundle mainBundle] loadNibNamed:@"CustomViewXIB" owner:nil options:nil] firstObject];

It will create the instance of CustomView class by using its corresponding XIB file.

Upvotes: 1

Related Questions