Search code examples
ioscgrect

add border in CGRect iOS


I want to add a border in a CGRect. Although previous solutions suggest either this:

CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
    CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
    CGContextFillRect(context, rectangle);

or something like this:

view.layer.borderWidth = 10;
view.layer.borderColor = [UIColor redColor].CGColor;

I cannot apply either of this in my approach.

In my mainView Controller I am having this code:

-(void)actionHint
{
    CGRect  viewRect = CGRectMake(kScreenWidth/2 -kMenuWidth, kScreenHeight/2-kMenuHeight - 70,kMenuWidth*10, kMenuHeight*4);
    HintMenu* hintMenu = [HintMenu viewWithRect:viewRect];
    [hintMenu.btnReveal addTarget:self action:@selector(actionReveal) forControlEvents:UIControlEventTouchUpInside];
    [hintMenu.btnNewAnag addTarget:self action:@selector(actionNewAnagram) forControlEvents:UIControlEventTouchUpInside];
    [self.gameView addSubview:hintMenu];
}

I am creating a game and I want a simple rect with some help actions to come on top of my current view. The code for viewRect is:

+(instancetype)viewWithRect:(CGRect)r
{
    HintMenu* hint = [[HintMenu alloc] initWithFrame:r];
    hint.userInteractionEnabled = YES;

    UIImage* image=[UIImage imageNamed:@"btn"];
    ... rest of items in the cgrect
    return hint;
}

Where should I add the code for adding the borders and what that code should be?


Solution

  • Your HintMenu is a type of view so in its initWithFrame method you can do:

    self.layer.borderWidth = 10;
    self.layer.borderColor = [UIColor redColor].CGColor;