子类化从nib加载的UIView子类 [英] Subclassing a UIView subclass loaded from a nib

查看:107
本文介绍了子类化从nib加载的UIView子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类 FooView ,它是 UIView 的子类,其视图是从一个nib,类似于:

I have a class, FooView, that is a subclass of UIView, and whose view is loaded from a nib, something like:

+ (instancetype)viewFromNib
{
    NSArray *xib = [[NSBundle mainBundle] loadNibNamed:@"FooView" owner:self options:nil];
    return [xib objectAtIndex:0];
}

nib本身的自定义类设置为 FooView身份检查器中的

The nib itself has its Custom Class set to FooView in the Identity Inspector.

这被实例化为:

FooView *view = [FooView viewFromNib];

这表现如您所愿。但是,当FooView本身被子类化为FooSubclassView,并实例化为:

This behaves as you'd expect. However, when FooView is itself subclassed as FooSubclassView, and instantiated as:

FooSubclassView *view = [FooSubclassView viewFromNib];

view 仍然是<$ c类型$ c> FooView ,而不是 FooSubclassView

用<$ c对类进行调整$ c> object_setClass 没有修复底层对象是 FooView 的实例的事实,因此在子类实例上调用的方法将是那些超类( FooView ),而不是 FooSubclassView

Swizzling the class with object_setClass doesn't fix the fact that the underlying object is an instance of FooView, and thus methods called on the subclass instance will be those of the superclass (FooView), not FooSubclassView.

如何更正此类以使子类具有正确的类型,而不必为每个子类创建新的nib,或者必须在每个子类中重新实现 viewFromNib ? / p>

How can I correct this so that subclasses are of the correct type, without having to create a new nib for every subclass, or having to reimplement viewFromNib in every subclass?

推荐答案

Swizzling不是(永远)答案。

Swizzling is not (ever) the answer.

问题在你的NIB;它被归档,对象[0]是 FooView 的实例,而不是 FooSubclassView 。如果要将相同的 NIB与不同的视图子类作为对象[0]加载,则需要将实例移出NIB的存档。

The problem is in your NIB; it is archived with object[0] being an instance of FooView, not FooSubclassView. If you want to load the same NIB with a different view subclass as object[0], you need to move the instance out of the NIB's archive.

可能最简单的事情是,因为你的类已经加载了NIB,所以要创建一个 FooView 或<$ c $的实例c> FooSubclassView 文件的所有者

Probably the easiest thing to do, since your class is already loading the NIB, is make an instance of FooView or FooSubclassView the File's Owner.

这个问题对文件的所有者<有一个不错的解释/ em>模式。请注意,你几乎已经在那里,因为你的类无论如何都在加载XIB / NIB。

This question has a decent explanation of the File's Owner pattern. Note that you are pretty much already there in that your class is what is loading the XIB/NIB anyway.

这是官方的文件所有者的文档

这篇关于子类化从nib加载的UIView子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆