繁体   English   中英

在UIView中绘制以及addSubview

[英]draw as well as addSubview in a UIView

嗨,我想使用Interface Builder在UIView上添加两个按钮,并在这两个按钮之间绘制一条线。 这怎么可能? 请提出建议。 谢谢

一个不使用drawrect的简单选项是将一个薄UIView放在两个按钮之间。 将视图的背景色设置为所需的线条颜色。

编辑:
您仍然可以使用瘦UIView并根据需要切换其可见性。
如果仍然要绘制线条,则可能需要创建一个自定义UIView。

@interface CustomView : UIView {
    UIButton *button1;
    UIButton *button2;
}
@end

@implementation CustomView

- (id) initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn1.frame = CGRectMake(20, 5, 80, 30);
        [btn1 setTitle:@"Button1" forState:UIControlStateNormal];
        [btn1 addTarget:self action:@selector(buttonPressed:) 
                forControlEvents:UIControlEventTouchUpInside];
        button1 = btn1;
        [self addSubview:btn1];

        UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn2.frame = CGRectMake(20, 60, 80, 30);
        [btn2 setTitle:@"Button2" forState:UIControlStateNormal];
        [btn2 addTarget:self action:@selector(buttonPressed:) 
                forControlEvents:UIControlEventTouchUpInside];
        button2 = btn2;
        [self addSubview:btn2];
    }
    return self;
}

-(void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    if (button1.selected)
        CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
    else
        CGContextSetRGBStrokeColor(context, 0.0, 1.0, 0.0, 1.0);
    CGContextSetLineWidth(context, 1.0);
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, 10.0, 45.0);
    CGContextAddLineToPoint(context, 150.0, 45.0);
    if (button1.selected)
    {
        CGContextAddLineToPoint(context, 180.0, 35.0);      
    }
    CGContextDrawPath(context, kCGPathStroke);
}

-(void)buttonPressed:(UIButton *)button
{
    button1.selected = !button1.selected;
    button2.selected = !button2.selected;
    [self setNeedsDisplay];
}

@end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM