1

我之前问过关于这个项目的另一个问题,Travis 非常有帮助。上一个问题

考虑到这个建议,我正在尝试为 C4Shape 类创建一个子类,我为 X 和 Y 位置值向该类添加了 2 个属性(均为浮点数)。我不只是调用 C4Shape 的 .center 属性的原因是因为要将它们添加到画布中,我更喜欢使用左上角而不是中心。

我正在尝试为这个新类编写自定义 Init 方法,但是出现错误。

这是我正在使用的自定义初始化代码:

自定义形状.m

- (id)initWithColor:(UIColor *)fillColor atX:(float)_xValue atY:(float)_yValue
{
CGRect frame = CGRectMake(_xValue, _yValue, 100, 100);
self = [customShape rect:frame];

self.lineWidth = 0.0f;
self.fillColor = fillColor;
self.xValue = _xValue;
self.yValue = _yValue;


return self;
}

C4WorkSpace.m

-(void)setup {
customShape *testShape = [[customShape alloc]initWithColor:[UIColor greenColor] atX:50.0f atY:50.0f];

[self.canvas addShape:testShape];
}

我怀疑罪魁祸首是self = [customShape rect:frame];这是我看到的警告:“不兼容的指针类型从'C4Shape *'分配给'customeShape *_strong'”

当我尝试运行它时引发的实际错误是:“由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'-[C4Shape setXValue:]:无法识别的选择器发送到实例 0x9812580'”

和以前一样,我正在制作可以保存颜色值的按钮,当您点击该按钮时,它将发送一个带有该按钮 fillColor 以及 iPad IP 的 UDP 数据包。

4

1 回答 1

2

您对 init 方法的实现非常接近。我将通过以下方式对其进行重组:

- (id)initWithColor:(UIColor *)aColor origin:(CGPoint)aPoint {
    self = [super init];
    if(self != nil) {
        CGRect frame = CGRectMake(0,0, 100, 100);
        [self rect:frame];
        self.lineWidth = 0.0f;
        self.fillColor = aColor;
        self.origin = aPoint;
    }
    return self;
}

有几点需要注意:

  1. 子类化时调用对象超类的 init 方法总是好的
  2. 最好init将子类的 包装在一个if语句中,检查超类 init 是否正确返回。
  3. 为您的新对象创建一个框架并直接调用rect:self
  4. origin每个可见的 C4 对象中都有一个点,因此您可以使用 a (左上角)设置原点,而不是直接使用xy值。CGPointorigin

然后,您需要将此方法添加到您的.h文件中:

@interface MyShape : C4Shape
-(id)initWithColor:(UIColor *)aColor origin:(CGPoint)aPoint;
@end

最后,您可以C4WorkSpace像这样创建您的形状:

MyShape *m = [[MyShape alloc] initWithColor:[UIColor darkGrayColor]
                                     origin:CGPointMake(100, 100)];

而且,如果你在你的点击方法中添加一条线,你可以检查按钮的原点:

-(void)heardTap:(NSNotification *)aNotification {
    MyShape *notificationShape = (MyShape *)[aNotification object];
    C4Log(@"%4.2f,%4.2f",notificationShape.center.x,notificationShape.center.y);
    C4Log(@"%4.2f,%4.2f",notificationShape.origin.x,notificationShape.origin.y);
    C4Log(@"%@",notificationShape.strokeColor);
}

虽然您可以使用xy值作为属性,但我建议使用CGPoint结构。几乎是一样的,除了当你从 C4 进入 Objective-C 时,你会注意到到处CGPoint都在使用其他CG几何结构。

于 2013-05-05T19:02:18.120 回答