如何在UIView上正确设置圆周围的对象

时间:2016-02-01 05:57:43

标签: ios swift

我已经编写了一些代码来围绕定位在自定义视图中心的圆圈放置对象,但它并不完美地围绕圆圈。我不知道代码在哪里出错。

enter image description here

以下是代码:

func createObjectsAroundCircle() {

    let center = CGPointMake(bounds.width/2 ,bounds.height/2)
    let radius : CGFloat = 100
    let count = 20

    var angle = CGFloat(2 * M_PI)
    let step = CGFloat(2 * M_PI) / CGFloat(count)

    let circlePath = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = circlePath.CGPath

    shapeLayer.fillColor = UIColor.clearColor().CGColor
    shapeLayer.strokeColor = UIColor.redColor().CGColor
    shapeLayer.lineWidth = 3.0

    self.layer.addSublayer(shapeLayer)

    // set objects around circle
    for var index = 0; index < count ; index++ {
        let x = cos(angle) * radius + center.x
        let y = sin(angle) * radius + center.y

        let label = UILabel()
        label.text = "\(index)"
        label.frame.origin.x = x
        label.frame.origin.y = y
        label.font = UIFont(name: "Arial", size: 20)
        label.textColor = UIColor.blackColor()
        label.sizeToFit()

        self.addSubview(label)
        angle += step 
    }
}

2 个答案:

答案 0 :(得分:14)

您的代码工作正常,只是计算逻辑错误。您应该尝试设置label.center而不是label.frame.origin

let label = UILabel()
label.text = "\(index)"
label.font = UIFont(name: "Arial", size: 20)
label.textColor = UIColor.blackColor()
label.sizeToFit()
label.frame.origin.x = x - label.frame.midX
label.frame.origin.y = y - label.frame.midY

在更改框架或设置标签sizeToFit()之前,请记住center。祝你好运!

答案 1 :(得分:0)

快捷键5

为方便起见,Masa S-AiYa问题逻辑+ Fahri Azimov答案已合并:

let center = CGPoint(x: bounds.size.width/2, y: bounds.size.width/2)
let radius: CGFloat = 100
let count = 20

let pi = Double.pi
var angle = CGFloat(2 * pi)
let step = CGFloat(2 *  pi) / CGFloat(count)

let circlePath = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(0), endAngle:CGFloat(pi * 2), clockwise: true)

let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath

shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.lineWidth = 3.0

layer.addSublayer(shapeLayer)

let font = UIFont(name: "Arial", size: 20)

// Set objects around the circle
for index in 0..<count {
    let label = UILabel()
    label.text = "\(index)"
    label.font = font
    label.textColor = .black
    // Remember to call 'sizeToFit()' before changing 'frame' or setting 'center' of the label!
    label.sizeToFit()
    
    // Position
    let x = cos(angle) * radius + center.x
    let y = sin(angle) * radius + center.y
    let midX = label.frame.x + label.frame.width / 2
    let mixY = label.frame.y + label.frame.height / 2
    
    label.frame.origin.x = x - midX
    label.frame.origin.y = y - mixY
    
    addSubview(label)
    angle += step
}