我在
swift项目中加载xib文件有一些奇怪的问题.这是非常令人沮丧的,因为我已经知道如何在Obj-C.但是因为迅捷是迅速的,所以你不能像你这样做.. .. /
所以我创建了IconTextFiled.xib和IconTextField.swift. (扩展UITextField)在xib我填充字段类在Idenity检查器和在故事板我做同样的一些textFields.所以我们很好,只需要从xib加载到init方法?没有.
在objc我会这样做
- - (instancetype)initWithCoder:(NSCoder *)coder
- {
- self = [super initWithCoder:coder];
- if (self) {
- NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"IconTextField" owner:self options:nil];
- self = [nib objectAtIndex:0];
- }
- return self;
- }
所以我想如果我翻译成swift它会是好的.
- required init(coder aDecoder: NSCoder) {
- super.init(coder: aDecoder)
- let nib:NSArray = NSBundle.mainBundle().loadNibNamed("IconTextField",owner: self,options: nil)
- self = nib.objectAtIndex(0)
- }
但是这不行.我不知道为什么,但它尝试创造更多的对象和崩溃
最后我发现扩展
- extension IconTextField {
- class func loadFromNibNamed(nibNamed: String,bundle : NSBundle? = nil) -> IconTextField? {
- return UINib(
- nibName: nibNamed,bundle: bundle
- ).instantiateWithOwner(nil,options: nil)[0] as? IconTextField
- }
- }
所以在ViewController看起来像
- @IBOutlet var password: IconTextField!
- override func viewDidLoad() {
- super.viewDidLoad()
- password = IconTextField.loadFromNibNamed("IconTextField")
- }
再次失败.你能告诉我如何加载和使用xib文件?
UPDATE
好吧,跟随丹尼尔之后
我当前的代码
- class IconTextField: UITextField {
- @IBOutlet var icon: UIImageView!
- @IBOutlet weak var view: UIView!
- required init(coder aDecoder: NSCoder) {
- super.init(coder: aDecoder)
- NSLog("initWithCoder \(self)")
- NSBundle.mainBundle().loadNibNamed("IconTextField",options: nil)
- self.addSubview(view)
- }
- }
那两个var连接到这些视图
Consoleo输出,大大多了,以EXC_BAD_ACCESS结尾
- 2014-10-24 10:09:09.984 testproject[20337:3757479] initWithCoder <stensgroup.IconTextField: 0x7be7bfb0;>
- 2014-10-24 10:09:09.984 testproject[20337:3757479] initWithCoder <stensgroup.IconTextField: 0x7be7ddf0;>
- 2014-10-24 10:09:09.985 testproject[20337:3757479] initWithCoder <stensgroup.IconTextField: 0x7be7fa20;>
- 2014-10-24 10:09:09.985 testproject[20337:3757479] initWithCoder <stensgroup.IconTextField: 0x7be814f0;>
- 2014-10-24 10:09:09.986 testproject[20337:3757479] initWithCoder <stensgroup.IconTextField: 0x7be830c0;>
- 2014-10-24 10:09:10.083 testproject[20337:3757479] initWithCoder <stensgroup.IconTextField: 0x7d183270;>
- 2014-10-24 10:09:10.084 testproject[20337:3757479] initWithCoder <stensgroup.IconTextField: 0x7d187cd0;>
- 2014-10-24 10:09:10.084 testproject[20337:3757479] initWithCoder <stensgroup.IconTextField: 0x7d189960;>
应该只有两个initWithCoder.它接收到func loadNibNamed调用initWithCoder
解决方法
这对我有用:
- class IconTextField: UITextField {
- @IBOutlet weak var view: UIView!
- @IBOutlet weak var test: UIButton!
- required init(coder: NSCoder) {
- super.init(coder: coder)
- NSBundle.mainBundle().loadNibNamed("IconTextField",options: nil)
- self.addSubview(view)
- assert(test != nil,"the button is conected just like it's supposed to be")
- }
- }
一旦loadNibNamed:owner:options:被称为视图和测试按钮按预期连接到插座.添加笔尖的视图自己的子视图层次结构使得笔尖的内容可见.