如何在Swift中的UIView中获取所有子视图的高度?

时间:2017-09-28 12:09:34

标签: swift uiview

如何获取UIView中所有子视图的高度并将其存储在公共变量中?

例如:

private FileSystem initFileSystem(URI uri) throws IOException {
    try {
        return FileSystems.newFileSystem(uri, Collections.emptyMap());
    }catch(IllegalArgumentException e) {
        return FileSystems.getDefault();
    }
}

2 个答案:

答案 0 :(得分:2)

获取当前视图的所有子视图,并使用mapreduce获取高度的总和。

let yPos = (view.subviews.map { $0.frame.height }).reduce(20, +)

答案 1 :(得分:1)

只需在视图中的子视图中运行循环:

var height:CGFloat = 0
for view in self.view.subviews {
    height = height + view.bounds.size.height
}
print(height) //total height of all subviews 

<强>更新

要为下一个子视图动态设置yPos,请运行循环以获得所需的多个视图:

    var yPos: CGFloat = 20 //initial yPos
    let uiHeight: CGFloat = 100 //fixed height for all views

    let someView = UIView(frame: CGRect(x: 100, y: yPos, width: 100, height: uiHeight))
    someView.backgroundColor = UIColor.green
    self.view.addSubview(someView)

    for _ in 0 ..< 3 {
        yPos = uiHeight + yPos + 2 // every time the loop runs, it will add the yPos of the previous view to current yPos
        let dynamicView = UIView(frame: CGRect(x: 100, y: yPos, width: 100, height: uiHeight))
        dynamicView.backgroundColor = UIColor.red
        self.view.addSubview(dynamicView)
    }

给你以下输出:

enter image description here

yPos = uiHeight + yPos + 2中的额外2用于填充。

<强>更新

设置标签,按钮和图像:

var yPos: CGFloat = 20 //initial yPos


for _ in 0 ..< 3 {
    let label = UILabel(frame: CGRect(x: 100, y: yPos, width: 100, height: 30))
    label.backgroundColor = UIColor.green
    label.text = "I am a label"
    self.view.addSubview(label)

    let imageView = UIImageView(frame: CGRect(x: 100, y: label.bounds.size.height + yPos, width: 100, height: 100))
    imageView.backgroundColor = UIColor.red
    imageView.image = UIImage(named: "sample")
    self.view.addSubview(imageView)

    let button = UIButton(frame: CGRect(x: 100, y: imageView.bounds.size.height + yPos, width: 100, height: 40))
    button.backgroundColor = UIColor.red
    button.setTitle("Click me!", for: .normal)
    self.view.addSubview(button)

    yPos = imageView.bounds.size.height + label.bounds.size.height + button.bounds.size.height + yPos
}

给我以下输出:

enter image description here