0

我想将 UILabel 放置在我的 Circle 的中心,但我似乎无法影响标签的位置。我似乎只能通过改变 CGRect 框架的高度来影响标签的位置。更改其他值根本不会影响位置。

这是我的 Circle.m 代码

- (id)initWithFrame:(CGRect)frame radius:(CGFloat)aRadius color:(UIColor*) aColor {
    self = [super initWithFrame:frame];
    if (self) {
        self.opaque = NO;

        [self setRadius:aRadius];
        [self setColor:aColor];
    }
    return self;
}


- (void)drawRect:(CGRect)rect
{

    NSString *string = @"1";
    UIFont* font = [UIFont systemFontOfSize:80];
    UILabel *label = [[UILabel alloc] init];
    label.text = string;
    label.textColor = [UIColor whiteColor];
    label.font = font;

    CGRect frame = label.frame;
    frame = CGRectMake(10, 10, 0, 85);
    label.frame = frame;

    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    [color setFill];
    circle = CGRectMake(0, 0, radius, radius);

    CGContextAddEllipseInRect(contextRef, circle);
    CGContextDrawPath (contextRef, kCGPathFill);
    [label drawRect:circle];

}

和我的 viewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    CGFloat radius = 70;
    CGRect position = CGRectMake(0, 0, radius, radius);
    Circle *myCircle = [[Circle alloc] initWithFrame:position radius:radius color:[UIColor redColor]];
    [self.view addSubview:myCircle];

}
4

1 回答 1

4

You should not be allocating new UIViews in drawRect: (and UILabel is a subclass of UIView). There are a few good ways of doing what you want, but none of them involve allocating a new UILabel in drawRect:.

One way is to make your Circle give itself a UILabel subview in its initializer, and center the label in layoutSubviews. Then in drawRect:, you just draw the circle and don't worry about drawing the label's text:

@implementation Circle {
    UILabel *_label;
}

@synthesize radius = _radius;
@synthesize color = _color;

- (id)initWithFrame:(CGRect)frame radius:(CGFloat)aRadius color:(UIColor*) aColor {
    self = [super initWithFrame:frame];
    if (self) {
        self.opaque = NO;

        [self setRadius:aRadius];
        [self setColor:aColor];

        _label = [[UILabel alloc] init];
        _label.font = [UIFont systemFontOfSize:80];
        _label.textColor = [UIColor whiteColor];
        _label.text = @"1";
        [_label sizeToFit];
        [self addSubview:_label];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    CGSize mySize = self.bounds.size;
    _label.center = CGPointMake(mySize.width * 0.5f, mySize.height * 0.5f);
}

- (void)drawRect:(CGRect)rect {
    [self.color setFill];
    CGSize mySize = self.bounds.size;
    CGFloat radius = self.radius;
    [[UIBezierPath bezierPathWithOvalInRect:CGRectMake(mySize.width * 0.5f, mySize.height * 0.5f, self.radius, self.radius)] fill];
}
于 2012-04-08T04:31:54.370 回答