iOS - 无法更改视图来源

时间:2014-07-13 10:18:09

标签: ios objective-c drawrect

我正在翻阅Big Nerd Ranch Guide第4版,但在处理视图和视图层次结构的章节中,我遇到了一些视图来源问题。

我已经在我的视图控制器中添加了一个自定义子视图,并覆盖了drawRect以在屏幕中间绘制一堆圆圈,然而,圆圈的原点不会发生变化而且它们都会被卡住左角,我不明白为什么。我真的只是复制了书中的代码,它似乎工作得很好。

这是我的drawRect:

- (void)drawRect:(CGRect)rect
{
    CGRect bounds = self.bounds;

    //Figure out the center of the bounds rectangle
    CGPoint center;
    center.x = bounds.origin.x + bounds.size.width/2.0;
    center.y = bounds.origin.y + bounds.size.height/2.0;

    //The largest circle will circumscribe the view
    float maxRadius = hypotf(bounds.size.width, bounds.size.height)/2.0;

    UIBezierPath *path = [[UIBezierPath alloc]init];

    //Loops and create multiple circles with different radii
    for (float currentRadius = maxRadius; currentRadius > 0 ; currentRadius -= 20) {
        [path moveToPoint:CGPointMake(center.x +currentRadius, center.y)];
        [path addArcWithCenter:center radius:currentRadius startAngle:0.0 endAngle:M_PI*2.0    clockwise:YES];
    }

    path.lineWidth = 10;
    [self.circleColor setStroke];
    [path stroke];
}

这是结果。一堆圆圈不在屏幕中央......

1 个答案:

答案 0 :(得分:1)

我会做一些事情。

  1. 通过创建另一个视图,更小,更亮的蓝色或任何其他视图来查找视图的来源,并说出centerView.center = biggerView.center。当然,把它搞定。

  2. 根据您的结果,适当移动您的框架/视图。

  3. autolayout工作正常吗?它定义得对吗?尝试将其关闭。

  4. 尝试使用self.center.x和y而不是制作另一个center.x / y。

  5. 实际上先这样做。记录或断点边界,并确保它的宽度不为0。您可以使用NSStringFromCGRect()

  6. 进行打印