最近在iOS開發中,需要使用iOS的畫線功能,畫線的方法可以寫在一個
Controller
視圖中,當然這不是最好的方式,建議還是自定義一個UIView
,并重寫drawRect:
方法,這樣后面方便使用,并且不會造成代碼的冗長與啰嗦。
一、新建一個類,繼承自UIView
重寫drawRect:方法:
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, 3); //線寬
CGContextSetAllowsAntialiasing(context, true);
CGContextSetRGBStrokeColor(context, 70.0 / 255.0, 241.0 / 255.0, 241.0 / 255.0, 1.0); //線的顏色
CGContextBeginPath(context);
CGContextMoveToPoint(context, 0, 0); //起點坐標
CGContextAddLineToPoint(context, self.frame.size.width, self.frame.size.height); //終點坐標
CGContextStrokePath(context);
}
二、在其他類中調用
- (void)viewDidLoad {
[super viewDidLoad];
CustomLine *line = [[CustomLine alloc] init];
line.backgroundColor = [UIColor whiteColor];
line.frame = self.view.frame;
[self.view addSubview:line];
}
三、需要注意的問題:
在這里直接運行,就會出現畫的線段,但是我在項目中寫的時候,發現畫線并沒有出現(項目使用的是swift),說明系統沒有自動的調用drawRect:
方法,這里就需要我們在Controller
視圖中手動的調用[line setNeedsDisplay];
這句話是手動的讓系統去調用drawRect:
方法。
注意:不要試圖手動去調用drawRect:方法,因為這是系統負責調用的。
運行截圖:
運行截圖