космическое положение объектов по пропорциям
Мой быстрый код ниже позиционирует объекты. Я хочу, чтобы оба объекта покрывали по 10 процентов оси x каждый. Итак, первый объект - fight[0].image, а второй объект - fight 1.image. Как вы можете видеть на изображении слева, это то, что производит текущий код ниже. Изображение справа - это то, что я хотел бы получить из кода. Поскольку я не могу ограничить приведенный ниже код, я не знаю, как достичь этого результата. Таким образом, изображение fight[0].image должно покрывать 10 процентов оси x, а изображение fight 1 должно покрывать следующие 10 процентов оси x. Вместе эти 2 объекта должны покрывать 20 процентов оси x.
https://stackru.com//images/7de8ce14683c69ef5f00eb25dfe51b35bbcaadf5.jpg
import UIKit
class ViewController: UIViewController {
let fight = (0..<10).map { _ in UIImageView() }
var textEnter = UITextField()
var g2 = UIPanGestureRecognizer()
var g3 = UIPanGestureRecognizer()
override func viewDidLoad() {
super.viewDidLoad()
fight[0].image = UIImage(named: "a.png")
fight[1].image = UIImage(named: "m.png")
fight.forEach{
$0.isUserInteractionEnabled = true
}
[textEnter].forEach{
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
$0.backgroundColor = .blue
}
g2 = UIPanGestureRecognizer(target: self, action: #selector(ViewController.g1Method))
g3 = UIPanGestureRecognizer(target: self, action: #selector(ViewController.g1Method))
fight[0].addGestureRecognizer(g2)
fight[1].addGestureRecognizer(g3)
fight.forEach{
$0.backgroundColor = .clear
view.addSubview($0)
}
// need a non-rendering "spacer" to vertically separate textEnter from Pic
let spacer = UILayoutGuide()
view.addLayoutGuide(spacer)
// NOTE: do NOT constrain any elements relative to fight views
NSLayoutConstraint.activate ([
// constrain textEnter top / leading / trailing to view
textEnter.topAnchor.constraint(equalTo: view.topAnchor, constant : 0),
textEnter.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant : 0),
textEnter.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant :0),
// constrain textEnter height to 0.1 * view height
textEnter.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.1, constant: 0),
// constrain spacer top to bottom of textEnter
spacer.topAnchor.constraint(equalTo: textEnter.bottomAnchor, constant: 0.0),
// constrain spacer leading to view leading
spacer.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0),
// constrain spacer height to 0.1 * view height
spacer.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.10),
// spacer width doesn't matter
spacer.widthAnchor.constraint(equalToConstant: 1.0),
])
textEnter.textAlignment = .center
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// set fight[0] frame *after* textEnter has been laid-out
fight[0].frame.size = CGSize(width: view.frame.width * 0.10, height: view.frame.height * 0.10)
let x = view.frame.origin.x
let y = textEnter.frame.origin.y + textEnter.frame.size.height
fight[0].frame.origin = CGPoint(x: x, y: y)
fight[1].frame.size = CGSize(width: view.frame.width * 0.10, height: view.frame.height * 0.10)
let x1 = view.frame.origin.x * 0.10
let y1 = textEnter.frame.origin.y + textEnter.frame.size.height
fight[1].frame.origin = CGPoint(x: x1, y: y1)
}
}
1 ответ
Вы, вероятно, хотите, чтобы ваш fight
изображения должны быть квадратными (чтобы изображение было круглым), поэтому рассчитайте ширину один раз как:
let w = view.frame.width * 0.10
и установите для высоты то же значение, что и для ширины
let h = w
Вы начнете с y
быть нижней частью textEnter
, а также x
как 0
, затем прокрутите просмотры изображений в вашем fight
массив, устанавливая фрейм и увеличивая x
по w
:
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
виды изображений, выровненные по виду (я использовал случайные цвета для фона):