ios - 如何制作一个 UIImageView,以编程方式在具有约束的容器中垂直居中

标签 ios objective-c iphone constraints

我想在容器 View (self.view) 中居中 UIImageView (self.showImageView)

我试过下面的代码,但没有用:

NSLayoutConstraint *xCenterConstraint = [NSLayoutConstraint constraintWithItem:self.showImageView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
[self.view addConstraint:xCenterConstraint];

NSLayoutConstraint *yCenterConstraint = [NSLayoutConstraint constraintWithItem:self.showImageView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
[self.view addConstraint:yCenterConstraint];

最佳答案

试试这个:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 100)];
    redView.backgroundColor = [UIColor redColor];
    redView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:redView];
    [redView addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:100]];
    [redView addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:200]];

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
    [self.view addSubview:redView];
}

关于ios - 如何制作一个 UIImageView,以编程方式在具有约束的容器中垂直居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27482671/

相关文章:

objective-c - 设置 SOCKS 代理配置后 CFStream 崩溃

iOS 7 - 禁用 UITabBarItem 色调颜色

iphone - 线程、优先级和放弃

iphone - NSPredicate 用于排除尚未保存在 NSFetchedResultsController 中的 NSManagedObjects

objective-c - 在哪里可以找到 Objective-C 2.0 的 EBNF 语法

iphone - 在 iOS7 中测试的 UINavigationBar 设置 tintcolor 不起作用?

iphone - 检查消息是否将使用 iMessage 或蜂窝网络发送

iphone - iOS - 是否有可能 [NSData dataWithContentsOfURL :url] would return only part of the bytes of the content?

ios - 如何动画 CAShapeLayer 路径变化?

ios - 为已经拥有由其他开发人员创建的应用程序的客户提交和 iOS 应用程序