硬编码的UIView与XIB UIView调整大小

时间:2014-06-20 11:34:48

标签: ios iphone objective-c autolayout

当有硬编码的UITextField时,我偶然发现如何布置UIImageViewUIImageView是硬编码的,让我说明一下:

//  Image
CGFloat xCenter = self.view.frame.size.width / 2.00;
CGFloat yCenter = self.view.frame.size.height / 2.00;



if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
    self.imageFrame = CGRectMake(xCenter + 115, yCenter - 425, 250, 250);
}

else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
    self.imageFrame = CGRectMake(xCenter - 125 , yCenter, 250, 250);
}

if ([[BNRImageStore sharedStore] imageForKey:self.item.itemKey]) {
    self.imageView = [[UIImageView alloc] initWithFrame:self.imageFrame];
    self.imageView.image = [[BNRImageStore sharedStore] imageForKey:self.item.itemKey];
    [self.imageView.layer setBorderColor:(__bridge CGColorRef)([UIColor blackColor])];
    [self.imageView.layer setBorderWidth:3.0];
    self.imageView.contentMode = UIViewContentModeScaleAspectFill;
    self.imageView.translatesAutoresizingMaskIntoConstraints = NO;

    [self.view addSubview:self.imageView];

    NSDictionary *nameMap =@{@"imageView": self.imageView,
                             @"nameLabel": self.nameLabel,
                             @"nameField": self.nameField};

    NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[nameLabel]-[nameField]-[imageView(==250)]-|" options:0 metrics:nil views:nameMap];

    [self.view addConstraints:@[horizontalConstraints]];
}

else {
    UIView *imageCanvasView = [[UIView alloc] initWithFrame:self.imageFrame];

    imageCanvasView.backgroundColor = [UIColor colorWithWhite:1.00 alpha:0.4];

    imageCanvasView.layer.borderWidth = 1.0f;
    imageCanvasView.layer.borderColor = [UIColor colorWithWhite:0.00 alpha:0.9].CGColor;
    [self.view addSubview:imageCanvasView];

    UILabel *addImageLabel = [[UILabel alloc] initWithFrame:self.imageFrame];
    addImageLabel.text = @"(tap to add image)";
    addImageLabel.font = [UIFont fontWithName:@"AvenirNext-UltraLight"
                                         size:20];
    addImageLabel.textColor = [UIColor WHITE_COLOR_DEBUG_FIX];
    addImageLabel.textAlignment = NSTextAlignmentCenter;
    addImageLabel.hidden = NO;

    [self.view addSubview:addImageLabel];
}

似乎这就是我需要的: iPhone

但不是在iPad中: iPad

UIImageView *imageView属性外,我使用自动布局制作了常量。由于XIB文件无法识别imageView,因此我无法设置它的约束。相反,我可以使用VFL,但约束在某些时候相交。因此我无法理解它。

有什么想法吗? (或者可能以某种方式?)

1 个答案:

答案 0 :(得分:0)

我有类似的问题,我通过在故事板或编程上创建两个持有者UIViews来解决它 - 一个持有表单,另一个持有硬编码的UIImageView。

如果您正在使用故事板:在这两个保持视图和包含表单的视图的子视图中设置约束。只需将UIImageView以编程方式放在图像保持视图的中心即可。