子类化 UIView 与 UIScrollView [英] Subclassing UIView vs UIScrollView
问题描述
好吧,这可能是不可能的,但我有一个类(称为 CompositeView
),它是 UIView
的子类.它使用一些核心图形工作根据某些选项生成自定义背景.不是一个庞大的班级,但随着我的需求变化/增加/无论什么都会增长.我遇到的问题是我在很多不同的地方经常使用这个类.但在一些地方,我需要它是 UIScrollView
的子类,而不是 UIView
.有趣的是,我可以简单地更改超类,并且一切正常.但我不仅不希望我的所有其他视图都成为 UIScrollView
,它还会干扰其中一些视图的操作.所以我需要一个类,它有时是 UIScrollView
的子类,有时是 UIView
的子类.
Ok, this might not be possible, but I've got a class (called CompositeView
) that's a subclasses UIView
. It uses some core graphics work to produce a custom background based on some options. Not a huge class, but bound to grow as my demands change/increase/whatever. The problem I'm having is I use this class a lot, in a lot of different places. But in a few of the places I need it to be a subclass of UIScrollView
instead of a UIView
. Interestingly enough, I can simply change the superclass and it all works perfectly fine. But not only do I not want all my other views to be a UIScrollView
, it also interferes with the operation of some of them. So I need a class that's sometimes a subclass of UIScrollView
and sometimes a subclass of UIView
.
现在,我从字面上复制了 CompositeView
的所有接口/实现,将类名更改为 CompositeScrollView
,并将其继承更改为 UIScrollView
.它工作正常,但现在我有两组代码做完全相同的事情,只是从不同的父类继承.这使得让他们都保持最新状态很痛苦.
For now, I've literally copied all of the interface/implementation of the CompositeView
, changed the class name to CompositeScrollView
, and changed it's inheritance to UIScrollView
. It works fine, but now I've got two sets of code that do exactly the same thing, just inherited from different parent classes. This makes keeping them both up to date a pain.
有没有更好的方法来做到这一点?
Is there a better way to do this?
推荐答案
单继承语言强制您使用委托.您可以将添加的功能分解为一个单独的类,您为派生类实例化该类,然后将派生类中的转发垫片写入实例.很痛苦.
Single inheritance languages force you to use delegation. You'd factor out the added functionality into a separate class that you instantiate for your derived classes and then write forwarding shims from the derived class to the instances. It's painful.
Objective C 有一些协议来描述添加的函数(任何未被覆盖的垫片),然后如果你没有编写垫片,编译器就会出错……你仍然需要手动完成.
Objective C has protocols which would describe the added functions (any shims that are not overrides) and then the compiler would error-out if you didn't write the shim ... which you still have to do manually.
Objective C 也有允许您扩展现有类的类别,但这些类别不能共享(您必须单独扩展每个类),因此它并没有真正的帮助.
Objective C also has categories that allow you to extend existing classes but these can't be shared (you have to extend each class individually) so it doesn't really help.
这篇关于子类化 UIView 与 UIScrollView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!