我有一個BoardViewController(UIViewController的),並需要繪製圓心,線到它的背景。對於這些座標線,我創建了一個自定義UIView類CoordinateView,它們作爲子視圖添加。即使在更改設備方向時,座標視圖也應居中並填滿整個屏幕。繪製和中心自定義的UIView作爲背景使用自動佈局
要做到這一點,我想用自動佈局在代碼實現。這裏是我的當前設置:
在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];
...
}
添加自動佈局神奇的coordinateView在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 coordinateView工作。
我該如何再次使用它?作爲soons爲我申請了自動佈局/ NSLayoutConstraint我coordinatesView的UIView似乎消失
這實際上增加背景繪製到一個UIViewController還是更直接繪製成的UIViewController一個不錯的辦法。 (如果是這樣會怎樣?)
我感謝您的幫助。
只是要注意的是「一般需要4個約束「可能會誤導人們認爲限制的數量很重要。不是。約束條件需要*足夠*,並導致一個精確的佈局。 – Daniel