【问题标题】:Auto Layout standard space between view and superview not working视图和超级视图之间的自动布局标准空间不起作用
【发布时间】:2015-03-26 19:15:40
【问题描述】:

我正在使用Auto Layout Visual Format Lanugage 使子视图的框架适合其父视图的框架,减去标准空间量(大约 8 像素)(“标准空间”在视觉格式语言中表示为 -) .

这是我的代码:

class ViewController: UIViewController {

    var imageView: UIImageView = UIImageView()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.redColor()

        imageView.backgroundColor = UIColor.greenColor()
        imageView.setTranslatesAutoresizingMaskIntoConstraints(false)
        self.view.addSubview(imageView)

        let viewsDict = ["imageView": imageView]

        let imageViewConstraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[imageView]-|",
            options: NSLayoutFormatOptions.allZeros,
            metrics: nil,
            views: viewsDict)
        self.view.addConstraints(imageViewConstraintsH)

        let constraintsV = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[imageView]-|",
            options: NSLayoutFormatOptions.allZeros,
            metrics: nil,
            views: viewsDict)
        self.view.addConstraints(constraintsV)
    }
}

正如您在下面的屏幕截图中看到的,标准间距是水平的,而不是垂直的:

【问题讨论】:

    标签: ios uikit autolayout


    【解决方案1】:

    我无法回答为什么它不起作用(Apple DTS 也不能),但您可以使用 superview 中的内置布局指南来完成同样的事情,如下所示:

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        id  topLayoutGuide = self.topLayoutGuide;
        id  bottomLayoutGuide = self.bottomLayoutGuide;
    
        UIImageView *imageView = [[UIImageView alloc]init];
        [imageView setTranslatesAutoresizingMaskIntoConstraints:false];
    
        NSDictionary *views = NSDictionaryOfVariableBindings(imageView, topLayoutGuide, bottomLayoutGuide);
    
    
        self.view.backgroundColor = [UIColor grayColor];
        imageView.backgroundColor = [UIColor whiteColor];
    
        [self.view addSubview:imageView];
    
        [self.view addConstraints:
        [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[imageView]-|"
                                                options:0
                                                metrics:nil
                                                  views:NSDictionaryOfVariableBindings(imageView)]
         ];
        [self.view addConstraints:
        [NSLayoutConstraint constraintsWithVisualFormat:@"V:[topLayoutGuide]-[imageView]-[bottomLayoutGuide]"
                                                options:0
                                                metrics:nil
                                                  views:views]
         ];
    
    }
    

    感谢 T. Cooper

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-24
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      相关资源
      最近更新 更多