简体   繁体   English

迅捷:如何在代码中使用约束与乘数

[英]swift: how to use constraints with multiplier in code

I have a custom view and I want to add an image such that it's bottom anchor is at 3/4 of the view. 我有一个自定义视图,我想添加一个图像,使其底部锚点位于视图的3/4。 In the storyboard I would just set a constraint with first item imgview.bottom, second item view.bottom, constant 0 and multiplier 0.75 在情节提要中,我将使用第一项imgview.bottom,第二项view.bottom,常数0和乘数0.75设置约束

In code I tried: 在代码中,我尝试过:

let imgview = UIImageView(image: img)
imgview.translatesAutoresizingMaskIntoConstraints = false
addSubview(imgview)
NSLayoutConstraint.activate([
    imgview.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.4),
    imgview.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.4),
    imgview.centerXAnchor.constraint(equalTo: centerXAnchor),
    imgview.bottomAnchor.constraint(equalToSystemSpacingBelow: bottomAnchor, multiplier: 0.75)
    ])

but the bottom of the image is even below the bottom of the view. 但是图像的底部甚至低于视图的底部。 If I use bottomAnchor.constraint(equalToSystemSpacingBelow: imgview.bottomAnchor, multiplier: 0.75) 如果我使用bottomAnchor.constraint(equalToSystemSpacingBelow: imgview.bottomAnchor, multiplier: 0.75)

It is above it but still too low. 它高于它,但仍然太低。 How do I do this? 我该怎么做呢?

I would have done it using equalTo:,constant: . 我会使用equalTo:,constant:完成的

let frameHeight = frame.height
let padding = frameHeight * 0.25
imgview.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -padding)

Frame value might return 0 if the view is not loaded yet. 如果尚未加载视图,则帧值可能返回0。

override func layoutSubviews() {
super.layoutSubviews()
if self.frame.height > 0 {
//Add constraints here
}
}

Use constraint creation for that last one the old-fashion way: 用最后一种方式对最后一种使用约束创建:

let imgview = UIImageView(image: img)
imgview.translatesAutoresizingMaskIntoConstraints = false
addSubview(imgview)
NSLayoutConstraint.activate([
    imgview.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.4),
    imgview.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.4),
    imgview.centerXAnchor.constraint(equalTo: centerXAnchor),
/// imgview.bottomAnchor.constraint(equalToSystemSpacingBelow: bottomAnchor, multiplier: 0.75)
    ])

let constraint = NSLayoutConstraint(item: imgview, attribute: .bottom, 
                                    relatedBy: .equal, 
                                    toItem: view, attribute: .bottom, 
                                    multiplier: 0.75, constant: 0)
constraint.isActive = true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM