将cgrect帧上的y值更改为屏幕顶部下方的80



我希望我的swift代码在屏幕上放置两个图像视图。图像视图是通过cgrect框架放置的。我想要的是box1从屏幕顶部覆盖到屏幕高度的80%。底部20%的高度应该用箱子2盖住。不知怎的,在y值上,我需要box2从屏幕顶部下方80开始。

import UIKit
class ViewController: UIViewController {



var box1 = UIImageView()
var box2 = UIImageView()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.

let VCframe = self.view.frame
let height = VCframe.height * 0.8

let height2 = VCframe.height * 0.2
let widthx = VCframe.width
view.addSubview(box1)
view.addSubview(box2)
box1.backgroundColor = .red
box2.backgroundColor = .blue


box1.frame = CGRect(x: 0, y: 0, width: widthx, height: height)
box2.frame = CGRect(x: 0, y: 0, width: widthx, height: height2)

}




}

所以我认为这就是您正在寻找的解决方案:

class ViewController: UIViewController {
var box1 = UIImageView()
var box2 = UIImageView()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.

let VCframe = self.view.frame
let height = VCframe.height * 0.8

let height2 = VCframe.height * 0.2
let widthx = VCframe.width
view.addSubview(box1)
view.addSubview(box2)
box1.backgroundColor = .red
box2.backgroundColor = .blue
box1.translatesAutoresizingMaskIntoConstraints = false
box2.translatesAutoresizingMaskIntoConstraints = false


box1.frame = CGRect(x: 0, y: 0, width: widthx, height: height)
box2.frame = CGRect(x: 0, y: height, width: widthx, height: height2)

}
}

然而,使用框架作为布局模式并不是一个好主意。

这可能就是你想要做的:

class ViewController: UIViewController {
var box1 = UIImageView()
var box2 = UIImageView()

override func viewDidLoad() {
super.viewDidLoad()
loadViews()
}

private func loadViews() {
view.addSubview(box1)
view.addSubview(box2)
box1.backgroundColor = .red
box2.backgroundColor = .blue
box1.translatesAutoresizingMaskIntoConstraints = false
box2.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([
box1.leadingAnchor.constraint(equalTo: view.leadingAnchor),
box1.trailingAnchor.constraint(equalTo: view.trailingAnchor),
box1.heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.height*0.8),
box1.topAnchor.constraint(equalTo: view.topAnchor),

box2.leadingAnchor.constraint(equalTo: view.leadingAnchor),
box2.trailingAnchor.constraint(equalTo: view.trailingAnchor),
box2.topAnchor.constraint(equalTo: box1.bottomAnchor),
box2.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
}

最新更新