我添加UIView
,其大小等于屏幕大小,而不是UIImageView
添加到此视图。我想将此UIImageView
设置在UIView
的正中心。因此,我以编程方式执行此操作,无法通过故事板进行约束。以下是我的代码:
UIView* viewForImage = [[UIView alloc] initWithFrame:screenRect];
CGRect rect = CGRectMake(0, 0, 100, 200);
UIImageView* imgcoverView = [[UIImageView alloc] initWithFrame:rect];
imgcoverView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.9];
imgcoverView.image = imgView.image;
[viewForImage addSubview:imgcoverView];
答案 0 :(得分:2)
imgcoverView.center = CGPointMake(viewForImage.frame.size.width/2,viewForImage.frame.size.height/2) ;
答案 1 :(得分:0)
请考虑设备的不同方向。我认为最好添加两个中心约束。
NSLayoutConstraint *xCenterConstraint = [NSLayoutConstraint constraintWithItem:imgcoverView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:viewForImage attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
[viewForImage addConstraint:xCenterConstraint];
NSLayoutConstraint *yCenterConstraint = [NSLayoutConstraint constraintWithItem:imgcoverView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:viewForImage attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
[viewForImage addConstraint:yCenterConstraint];
答案 2 :(得分:0)
imgcoverView.frame =
CGRectMake(viewForImage.frame.origin.x + (viewForImage.frame.size.width - imgcoverView.frame.size.width)/2,
viewForImage.frame.origin.y + (viewForImage.frame.size.height - imgcoverView.frame.size.height)/2,
imgcoverView.frame.size.width,
imgcoverView.frame.size.height);
答案 3 :(得分:0)
你可以通过约束来做到这一点!
在容器中仅设置两个约束水平中心,在容器中设置垂直中心