gpt4 book ai didi

ios - StackView 中的 UIView - 层的位置

转载 作者:行者123 更新时间:2023-11-30 11:38:29 26 4
gpt4 key购买 nike

我对 Swift 和一般编码还很陌生。我试图创建 4 个简单的灰色圆圈,它们位于 2 个 stackView 内的 4 个 UIView 内...等等

对于 4 个 UIView,我基本上将它们放在屏幕中心的网格正方形中,为了清楚起见,我将在下面添加屏幕截图。目前,它似乎将底部圆圈渲染得远远低于我在 XCode IB 中布置的框。

我尝试了几种不同的方法来尝试让圆圈正确定位,但我遇到了困难,似乎无法弄清楚为什么它不起作用。如果我在 UIViews 中添加一个 UIView(名为“topLeftBox”、“topRightBox”...等),我可以让它们正确定位。虽然这是一个简单的解决方法,但我只是想理解为什么我不能只在原始 4 个 UIView 中添加图层。

任何帮助将不胜感激,并对明显的新手错误提前表示歉意!

这是现在代码和 XCodeIB 的输出屏幕截图:

XCode Storyboard Grey Circles Simulator Output

这是代码:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var topLeftBox: UIView!
@IBOutlet weak var topRightBox: UIView!
@IBOutlet weak var bottomLeftBox: UIView!
@IBOutlet weak var bottomRightBox: UIView!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
drawCircle(box: topLeftBox)
drawCircle(box: bottomLeftBox)
drawCircle(box: topRightBox)
drawCircle(box: bottomRightBox)
}


func createCircle(lineColor: UIColor, strokeEnd: CGFloat) -> CAShapeLayer {

let layer = CAShapeLayer()
let circularPath = UIBezierPath(arcCenter: .zero, radius: 50, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
// Styling for the circular line
layer.path = circularPath.cgPath
layer.strokeColor = lineColor.cgColor
layer.fillColor = UIColor.clear.cgColor
layer.lineWidth = 10
layer.lineCap = kCALineCapRound
layer.strokeEnd = strokeEnd
layer.transform = CATransform3DMakeRotation(-CGFloat.pi/2, 0, 0, 1)

return layer

// Style the track

}

fileprivate func drawCircle(box: UIView) {

// Create Circles
let trackLayer = createCircle(lineColor: .lightGray, strokeEnd: 1)
box.layer.addSublayer(trackLayer)
trackLayer.position = box.center

}


}

最佳答案

你的问题是这一行:

trackLayer.position = box.center

这是使用盒子的frame的中心,它位于其父 View 的坐标系中。您需要盒子本身坐标系中的盒子中心(即它的边界)。

将上面的行替换为:

trackLayer.position = CGPoint(x: box.bounds.midX, y: box.bounds.midY)

关于ios - StackView 中的 UIView - 层的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49474649/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com