2010-12-09 34 views

回答

3

一個不使用drawrect的簡單選項就是在兩個按鈕之間放一個瘦UIView。將視圖的背景色設置爲所需的線顏色。

編輯:
您仍然可以使用瘦UIViews並根據需要切換其可見性。
如果您仍想繪製線條,則可能需要創建自定義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 
+0

這是一個不錯的選擇,但我想畫線。基本上,當一個按鈕處於選定狀態時,其他部分將被繪製,其他部分則不會被繪製,其他部分保持原樣。反之亦然 – Nishit 2010-12-09 13:55:49