Swift 按比例对对象进行空间定位
我下面的swift代码是定位对象。我希望两个对象都覆盖x轴的10%。因此,第一个对象是fight[0]。image,第二个对象是fight.image。正如您在左边的图像上看到的,下面的当前代码正在生成什么。右边的图像是我希望代码产生的。由于我不能约束下面的代码,我不知道如何实现这个结果。所以战斗[0]。图像应该覆盖x轴的10%,然后战斗。图像应该覆盖x轴的下一个10%。这两个对象加在一起应该覆盖x轴的20%Swift 按比例对对象进行空间定位,swift,nslayoutconstraint,cgpoint,cgsize,uilayoutguide,Swift,Nslayoutconstraint,Cgpoint,Cgsize,Uilayoutguide,我下面的swift代码是定位对象。我希望两个对象都覆盖x轴的10%。因此,第一个对象是fight[0]。image,第二个对象是fight.image。正如您在左边的图像上看到的,下面的当前代码正在生成什么。右边的图像是我希望代码产生的。由于我不能约束下面的代码,我不知道如何实现这个结果。所以战斗[0]。图像应该覆盖x轴的10%,然后战斗。图像应该覆盖x轴的下一个10%。这两个对象加在一起应该覆盖x轴的20% 导入UIKit 类ViewController:UIViewController{
导入UIKit
类ViewController:UIViewController{
让fight=(0..您可能希望您的fight
图像视图为方形(因此图像将为圆形),因此计算一次宽度,如下所示:
let w = view.frame.width * 0.10
并将高度设置为与宽度相同的值
let h = w
您将从y
作为textEnter
的底部开始,并将x
作为0
,然后在fight
数组中的图像视图中循环,设置帧并按w
递增x
:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// set fight frames *after* textEnter has been laid-out
// width should be 10% of view width
let w = view.frame.width * 0.10
// height should be the same as width
let h = w
// start x-position at 0
var x: CGFloat = 0
// y-position is bottom of textEnter frame
let y = textEnter.frame.origin.y + textEnter.frame.size.height
// set frames for all imageViews in fight array
fight.forEach { v in
// set the frame
v.frame = CGRect(x: x, y: y, width: w, height: h)
// increment x by the width
x += w
}
}
现在,您将有10个fight
图像视图在视图中对齐(我使用随机颜色作为背景):
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// set fight frames *after* textEnter has been laid-out
// width should be 10% of view width
let w = view.frame.width * 0.10
// height should be the same as width
let h = w
// start x-position at 0
var x: CGFloat = 0
// y-position is bottom of textEnter frame
let y = textEnter.frame.origin.y + textEnter.frame.size.height
// set frames for all imageViews in fight array
fight.forEach { v in
// set the frame
v.frame = CGRect(x: x, y: y, width: w, height: h)
// increment x by the width
x += w
}
}