【发布时间】:2013-01-19 19:51:54
【问题描述】:
我有一个 BoardViewController (UIViewController),需要在其背景中绘制居中坐标线。对于这些坐标线,我创建了一个自定义 UIView 类 CoordinateView,它被添加为子视图。即使更改设备方向,坐标视图也应居中并填充整个屏幕。
为此,我想使用在代码中实现的自动布局。这是我当前的设置:
在CoordinatesView (UIView) 类中自定义绘制方法 用于坐标线
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
CGContextSetLineWidth(context, 1.0);
CGContextMoveToPoint(context, self.bounds.size.width/2,0);
CGContextAddLineToPoint(context, self.bounds.size.width/2,self.bounds.size.height);
CGContextStrokePath(context);
CGContextMoveToPoint(context, 0,self.bounds.size.height/2);
CGContextAddLineToPoint(context, self.bounds.size.width,self.bounds.size.height/2);
CGContextStrokePath(context);
}
初始化 BoardViewController
中的这个coordinatesView对象- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
...
coordinatesView = [[CoordinatesView alloc]initWithFrame:self.view.frame];
[coordinatesView setBackgroundColor:[UIColor redColor]];
[coordinatesView clipsToBounds];
[coordinatesView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:coordinatesView];
[self.view sendSubviewToBack:coordinatesView];
...
}
在 BoardViewController 的 viewWillAppear 函数中为坐标视图添加 自动布局 魔法
-(void)viewWillAppear:(BOOL)animated{
...
NSLayoutConstraint *constraintCoordinatesCenterX =[NSLayoutConstraint
constraintWithItem:self.view
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:coordinatesView
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:1];
NSLayoutConstraint *constraintCoordinatesCenterY =[NSLayoutConstraint
constraintWithItem:self.view
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:coordinatesView
attribute:NSLayoutAttributeCenterY
multiplier:1.0
constant:1];
[self.view addConstraint: constraintCoordinatesCenterX];
[self.view addConstraint: constraintCoordinatesCenterY];
...
}
注意:这种方法适用于我使用 UIImageView 图像作为坐标,但不适用于自定义 UIView 坐标视图。
如何让它再次工作?一旦我应用自动布局/NSLayoutConstraint,我的坐标视图 UIView 似乎消失了
这实际上是向 UIViewController 添加背景绘图的好方法还是直接绘制到 UIViewController 中更好。 (如果是这样,那会是什么样子?)
感谢您对此提供的帮助。
【问题讨论】:
标签: ios objective-c uiview drawing