swift 如何将视图添加到可用空间?

pokxtpni  于 2023-08-02  发布在  Swift
关注(0)|答案(1)|浏览(84)

在我的应用程序中,正方形必须在一个空的空间中彼此相邻。正方形的宽度和高度由步进器确定。
我试过这段代码,但我不知道如何确定一个新正方形的x和y位置

@objc private func goButtonPressed() {
        let squareView: UIView = {
            let square = UIView()
            square.backgroundColor = .blue
            square.frame.size = CGSize(width: Int(stepperLabel.text!)!, height: Int(stepperLabel.text!)!)
            square.frame.origin = CGPoint(x: 0, y: 0)
            return square
        }()
        gameZone.addSubview(squareView)
    }

字符串
Screenshot

7eumitmz

7eumitmz1#

下面是一个在xcode playground上编写的简单示例。这个想法是递增到变量currentRowcurrentColumn,然后通过乘以平方宽度将其转换为x和y。

import PlaygroundSupport
import UIKit
import Foundation
import PlaygroundSupport

class ExampleViewController: UIViewController {

    let squaresByLine = 4
    var currentRow = 0
    var currentColumn = 0

    lazy var frameSize: CGSize = {
        let width = (view.frame.width / 4)
        return CGSize(width: width, height: width)
    }()

    private lazy var uiButton = {
        let btn = UIButton()
        btn.translatesAutoresizingMaskIntoConstraints = false
        btn.setTitle("Add", for: .normal)
        btn.setTitleColor(.black, for: .normal)
        btn.addAction(UIAction(handler: { [weak self] _ in
            self?.goButtonPressed()
        }), for: .touchUpInside)
        btn.backgroundColor = .green
        return btn
    }()

    private func goButtonPressed() {
        let x = CGFloat(currentColumn) * frameSize.width
        let y = CGFloat(currentRow) * frameSize.width

        debugPrint(x, y)
        let squareView: UIView = {
            let square = UIView()
            square.backgroundColor = .blue
            square.frame.size = frameSize
            square.frame.origin = CGPoint(x: x, y: y)
            return square
        }()
        view.addSubview(squareView)

        if currentColumn + 1 > squaresByLine {
            currentColumn = 0
            currentRow += 1
        } else {
            currentColumn += 1
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(uiButton)

        NSLayoutConstraint.activate([
            uiButton.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            uiButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
            uiButton.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            uiButton.heightAnchor.constraint(equalToConstant: 80)
        ])
    }

}

let viewController = ExampleViewController()
PlaygroundPage.current.liveView = UINavigationController(rootViewController: viewController)

字符串

相关问题