1
我想在網格中顯示水平和/或垂直線。所以我創建了一個UIView
子類GridLines
,它在drawRect:
中畫線。然後我創建其中兩個(一個垂直,一個不),並將它們作爲子視圖添加到我的主視圖(Canvas
)中,同時導出UIView
。我添加到Canvas
的其他自定義子視圖已正確顯示,刪除等,但GridLines
對象不是,並且它們的drawRect:
也不會被調用。當我在[Canvas drawRect:]
(現在已禁用)中繪製了此繪圖代碼時,它將正確顯示網格。UIView的drawRect沒有被調用
回頭看類似的問題,似乎大多數人遇到這個問題都在UIView
派生類中調用drawRect
,但我的是UIView
。
我失去了一些東西在這裏?
GridLines.h:
#import <UIKit/UIKit.h>
@interface GridLines : UIView
{
BOOL mVertical;
}
- (id) initWithFrame: (CGRect) _frame vertical: (BOOL) _vertical;
@end
GridLines.m:
#import "GridLines.h"
@implementation GridLines
- (id) initWithFrame: (CGRect) _frame vertical: (BOOL) _vertical
{
if ((self = [super initWithFrame: _frame]))
{
mVertical = _vertical;
}
return self;
}
- (void) drawRect: (CGRect) _rect
{
NSLog(@"[GridLines drawRect]");
CGContextRef context = UIGraphicsGetCurrentContext();
[[UIColor clearColor] set];
UIRectFill([self bounds]);
if (mVertical)
{
for (int i = 50; i < self.frame.size.width; i += 50)
{
CGContextBeginPath(context);
CGContextMoveToPoint(context, (CGFloat)i, 0.0);
CGContextAddLineToPoint(context, (CGFloat)i, self.frame.size.height);
[[UIColor grayColor] setStroke];
CGContextSetLineWidth(context, 1.0);
CGContextDrawPath(context, kCGPathFillStroke);
}
}
else
{
for (int j = 50; j < self.frame.size.height; j += 50)
{
CGContextBeginPath(context);
CGContextMoveToPoint(context, 0.0, (CGFloat)j);
CGContextAddLineToPoint(context, self.frame.size.width, (CGFloat)j);
[[UIColor grayColor] setStroke];
CGContextSetLineWidth(context, 1.0);
CGContextDrawPath(context, kCGPathFillStroke);
}
}
}
@end
在另一個UIView的派生類:
- (void) createGrids
{
mHorizontalLines = [[GridLines alloc] initWithFrame: self.frame vertical: NO];
mVerticalLines = [[GridLines alloc] initWithFrame: self.frame vertical: YES];
[self addSubview: mHorizontalLines];
[self addSubview: mVerticalLines];
}