0

我正在尝试使用自定义视图使我的主 ViewController 将多个自定义 UIView 绘制到主视图,但不知何故它们没有绘制,我正在尝试绘制点。

我的代码是:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    MyCustomView *myView = (MyCustomView *)self.view;

    myView.xAxisLabel1 = @"customlabels 1";
    myView.xAxisLabel2 = @"customlabels 2";
    myView.xAxisLabel3 = @"customlabels 3";
    myView.xAxisLabel4 = @"customlabels 4";

    CustomDotView *newDot = [[CustomDotView alloc] initWithPointAtXCord:10 andYCord:10 withRadius:10 andColor:[UIColor redColor]];

    [self.view addSubview:newDot];


}

但这不起作用,我想知道我的 CustomDotView 的构造函数是正确的还是我做错了什么

这是我的 CustomDotView 构造函数

-(id)initWithPointAtXCord:(float)xCord andYCord:(float)yCord withRadius:(float)radius andColor:(UIColor *)color {

    self = [super init];
    self.color = color;
    self.xCordenate = xCord;
    self.yCordenate = yCord;
    self.radius = radius;

    return self;

}
- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetLineWidth(context, 2.0);
    CGContextSetStrokeColorWithColor(context, color.CGColor);
    CGContextSetFillColorWithColor(context, color.CGColor);

    CGRect currentRect = CGRectMake(xCordenate, yCordenate, radius * 2 , radius * 2);

    NSLog(@"draw point?");

    CGContextAddEllipseInRect(context, currentRect);
    CGContextDrawPath(context, kCGPathFillStroke);
}

有什么建议么?

4

1 回答 1

2

好的,我继续在 Xcode 中写了这个,效果很好。这是我能想到的最简单的用例;这是里面的一个空白UIViewController

@implementation ViewController

- (void)viewDidLoad
{

    CustomDotView *newDot = [[CustomDotView alloc] initWithPointAtXCord:10 andYCord:10 withRadius:10 andColor:[UIColor redColor]];

    [self.view addSubview:newDot];

}

@end


@implementation CustomDotView

-(id)initWithPointAtXCord:(float)inputXCoord andYCord:(float)inputYCoord withRadius:(float)inputRadius andColor:(UIColor *)inputColor
{
    xCoord = inputXCoord;
    yCoord = inputYCoord;
    color = inputColor;
    radius = inputRadius;

    self = [super initWithFrame: CGRectMake(xCoord, yCoord, radius * 2, radius * 2)];

    self.backgroundColor = [UIColor clearColor];

    return self;

}
- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetLineWidth(context, 1.0);
    CGContextSetStrokeColorWithColor(context, color.CGColor);
    CGContextSetFillColorWithColor(context, color.CGColor);


    CGContextAddEllipseInRect(context, rect);
    CGContextDrawPath(context, kCGPathFill);
}


@end

如果你想移动 Dot,只需简单地改变它的框架。

于 2012-08-31T00:23:44.163 回答