UIButton显示正方形

时间:2014-05-08 06:35:09

标签: objective-c

这是我在我的类shape.h(子类UIView)

中绘制正方形的代码
- (void)drawRect:(CGRect)rect
{
        //Square

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);

CGContextSetStrokeColorWithColor(context,
                                 [UIColor blueColor].CGColor);
 CGRect rectangle = CGRectMake(20,20,80,80);
CGContextAddRect(context, rectangle);
CGContextStrokePath(context);
}

我需要帮助的是将我的代码并将其实现到我的ViewController(h)中的按钮中。说每当我触摸按钮时,我希望我的方块出现。我不确定我是否正确解释我的自我,如果我错了就纠正我。

1 个答案:

答案 0 :(得分:1)

我会采取另一种方式:

这是按下按钮时调用的IBAction:

-(IBAction)buttonPressed:(id)sender
{
 UIView *square = [[UIView alloc] init];
 square.frame = CGRectMake(20, 20, 80, 80);
 square.backgroundColor = [UIColor blueColor];
 [self.view addSubview:square];
}

这是一个圆圈的IBAction:

-(IBAction)buttonPressed:(id)sender
    {
     UIView *circle = [[UIView alloc] init];
     circle.frame = CGRectMake(20, 20, 80, 80);
     circle.backgroundColor = [UIColor blueColor];
     circle.layer.cornerRadius = circle.frame.size.height/2;
     [self.view circle];
    }

这就是你想要的吗?你不需要额外的UIView子类。

要将IBAction连接到UIButton,请右键单击界面构建器,从按钮​​到代码中的此方法,或者像这样:

[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

如果你想绘制更复杂的东西(比如三角形),你可以继承UIView。上面的代码是为了一些非常简单的事情。以下是三角形的一些示例代码,但我认为您明白了这一点:

ViewController.m:

#import "ViewController.h"
#import "triangle.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
    [button setTitle:@"Press me" forState:UIControlStateNormal];
    button.backgroundColor = [UIColor blackColor];
    button.titleLabel.textColor = [UIColor whiteColor];
    [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

-(IBAction)buttonPressed:(id)sender
{
    triangle *view = [[triangle alloc] initWithFrame:CGRectMake(0, 80, 200, 200)];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
}

@end

triangle.m:

#import "triangle.h"

@implementation triangle

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

    CGContextBeginPath(ctx);
    CGContextMoveToPoint   (ctx, CGRectGetMinX(rect), CGRectGetMinY(rect));  // top left
    CGContextAddLineToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMidY(rect));  // mid right
    CGContextAddLineToPoint(ctx, CGRectGetMinX(rect), CGRectGetMaxY(rect));  // bottom left
    CGContextClosePath(ctx);

    CGContextSetRGBFillColor(ctx, 100/255.f, 100/255.f, 100/255.f, 1);
    CGContextFillPath(ctx);
}

@end