Objective c 在现有uiview问题上绘制矩形

Objective c 在现有uiview问题上绘制矩形,objective-c,ios4,xcode4.2,Objective C,Ios4,Xcode4.2,我有一个基于视图控制器的应用程序,其中包含多个视图,我根据某些逻辑显示/隐藏这些视图。我想画一个矩形,它将是UIView的大小,以便使它像一个框架/边框形状 我在画矩形时遇到了问题。我知道下面的代码应该可以做到这一点,但我不确定为什么这个方法没有被调用或触发。我也没有看到(void)drawRect:(CGRect)rect方法在任何地方生成,所以我自己放置了它。我不知道我在这里遗漏了什么 - (void)drawRect:(CGRect)rect; { CGContextRef

我有一个基于视图控制器的应用程序,其中包含多个视图,我根据某些逻辑显示/隐藏这些视图。我想画一个矩形,它将是UIView的大小,以便使它像一个框架/边框形状

我在画矩形时遇到了问题。我知道下面的代码应该可以做到这一点,但我不确定为什么这个方法没有被调用或触发。我也没有看到(void)drawRect:(CGRect)rect方法在任何地方生成,所以我自己放置了它。我不知道我在这里遗漏了什么

- (void)drawRect:(CGRect)rect;
{   
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetRGBStrokeColor(context, 1.0, 1.0, 0.0, 1.0); // yellow line

    CGContextBeginPath(context);

    CGContextMoveToPoint(context, 50.0, 50.0); //start point
    CGContextAddLineToPoint(context, 250.0, 100.0);
    CGContextAddLineToPoint(context, 250.0, 350.0);
    CGContextAddLineToPoint(context, 50.0, 350.0); // end path

    CGContextClosePath(context); // close path

    CGContextSetLineWidth(context, 8.0); // this is set from now on until you explicitly change it

    CGContextStrokePath(context); // do actual stroking

    CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 0.5); // green color, half transparent
    CGContextFillRect(context, CGRectMake(20.0, 250.0, 128.0, 128.0)); // a square at the bottom left-hand corner
}

只是猜测,但是您是否告诉
UIView
重新显示自己

[myUIView setNeedsDisplay];

只有这样才能调用
drawRect:

如果您只需要添加一个简单的矩形边框,只需在
视图中执行以下操作即可显示:
视图控制器

- (void) viewWillAppear:(BOOL)animated
{
   //Simple border on the main view
   self.view.layer.borderColor = [UIColor redColor].CGColor;
   self.view.layer.borderWidth = 2;

   //Or a simple rectangle to place at x,h within the main view 
   UIView *test = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
   test.backgroundColor = [UIColor redColor];
   [self.view addSubview:test];
}
希望这有帮助

首先创建一个类(
YourView
),它是
UIView
的子类。您可以在viewController中实现代码

- (void)viewDidLoad
{
   YourView *temp = [[YourView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];

    [self.view addSubview:temp];
}
YourView.m
文件中编写方法(
-(void)drawRect:(CGRect)rect
)。
像这样试试。我认为这会对您有所帮助。

drawRect:
是UIView上的一个方法,所以您是将此代码放在视图控制器中还是将UIView子类化了?@Brian,我将其放在视图控制器中。UIView的子类是什么意思,用于什么目的?谢谢,谢谢。我添加了self.view.layer.cornerRadius=10.0f;创建圆角,它做得很好,但圆角后面显示白色背景,而我的uiview背景为黑色。知道为什么在显示角的同时显示白色背景吗?确定要在主视图上显示圆形边框吗?如果是这样,那么最好将self.view的背景色设置为您希望角点的任何颜色,然后添加另一个具有圆角的UIView(如上面的示例代码中所示)。