HTML5   发布时间:2022-04-27  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了iOS子类化自定义类大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我在编写关于类继承的想法时遇到了麻烦.我想在应用程序中创建一个类似界面的仪表板,我可能在该仪表板视图上有10个小部件/小程序.所有这些小面板/小部件将具有基本相同的外观,顶部的标题,顶部的边框,按钮行和图形.
假设我创建了一个名为’Dashlet’的UI视图的子类,其中包含属性和出口,并创建具有适当布局和连接出口等的XIB文件.

现在我想创建几个“Dashlet”视图的子类,它只会以不同的方式处理数据,并绘制不同的图形.我当前的代码看起来像这样

Dashlet.h

@interface Dashlet : UIView{
@private
    UILabel *title;
    UIView *controls;
    UIView *graph;    
}
@property (weak,nonatomiC) IBOutlet UILabel *title;
@property (weak,nonatomiC) IBOutlet UIView *controls;
@property (weak,nonatomiC) IBOutlet UIView *graph;

-(Dashlet*)initWithParams:(NSMutableDictionary *)params;
-(void)someDummymethod;
@end

在Dashlet.m

- (id) init {
    self = [super init];
    //Basic empty init...
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

    }
    return self;
}

-(id)initWithParams:(NSMutableDictionary *)params
{
    self = [super init];
    if (self) {
        self = [[[NSBundle mainBundle] loadNibNamed:@"Dashlet" owner:nil options:nil] lastObject];
        //some init code
    }
    return self;
}

现在让我们说我创建了一个名为CustomDashlet.h的子类:

@interface CustomDashlet : Dashlet
@property (nonatomic,strong) NSString* test;
-(void)testMethod;
-(void)someDummymethod;
@end

和CustomDashlet.m

-(id)init{
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

    }
    return self;
}

-(id)initWithParams:(NSMutableDictionary *)parameters
{
   self = [super initWithParams:parameters];
   if (self) {
      //do some stuff 
   }
   return self;
}

这种,有点工作,但我需要覆盖超类中声明的一些方法,甚至添加我自己的一些方法.每当我尝试在CustomDashlet.m中做这样的事情

[self someDummymethod]甚至[self testMethod]我得到一个像这样的异常错误

NSInvalidArgumentexception',reason: '-[Dashlet testMethod]: unrecognized SELEctor sent to instance

我甚至这样做了吗?我错过了什么?我应该以其他方式做这项工作吗?如果有人有任何建议,请随时分享您的想法,谢谢您的帮助.

解决方法

问题是
SALEsDashlet *SALEs = [[SALEsDashlet alloc] initWithParams:nil];

不会按预期返回SALEsDashlet实例,而是返回Dashlet实例.
这是发生的事情:

> [SALEsDashlet alloc]分配SALEsDashlet的实例.
>使用此实例调用initWithParams:的子类实现,
调用self = [super initWithParams:parameters].
> initWithParams的超类实现丢弃self和
用从Nib文件加载的新实例覆盖它.这是一个实例
达什莱特
>返回此新实例.

因此SALEsDashlet * SALEs“仅”是Dashlet,并且调用任何子类
它上面的方法抛出一个“未知选择器”异常.

您无法更改Nib文件中加载的对象类型.你可以创建第二个包含SALEsDashlet对象的Nib文件.如果子类的主要目的是要添加其他方法,最简单的解决方案是添加这些方法在Dashlet类的类别中.

大佬总结

以上是大佬教程为你收集整理的iOS子类化自定义类全部内容,希望文章能够帮你解决iOS子类化自定义类所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。