ios - 如何将文本居中放置在圆圈中间?

标签 ios swift uilabel calayer uibezierpath

我制作了一个圆形类,但我想将文本放在它的正中央。

字体大小无关紧要,文本应始终显示在中间。

到目前为止,我只是简单地尝试了任意值,直到它离中心足够近为止。必须有更简单的方法。

import UIKit


class CircleView: UIView {
let circleLayer: CAShapeLayer  = CAShapeLayer()

init(frame: CGRect, innerColor: CGColor = Colors.colorWithHexString("#858585").CGColor, rimColor: CGColor = UIColor.blueColor().CGColor) {
    super.init(frame: frame)
    self.backgroundColor = UIColor.clearColor()
    let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: (frame.size.width - 10)/2, startAngle: 0.0, endAngle: CGFloat(M_PI * 2.0), clockwise: true)

    // Setup the CAShapeLayer
    circleLayer.path = circlePath.CGPath
    circleLayer.fillColor = innerColor
    circleLayer.strokeColor = rimColor
    circleLayer.lineWidth = 5.0

    // Don't draw the circle at start
    circleLayer.strokeEnd = 1.0
    layer.addSublayer(circleLayer)
}

func animateCircle(duration: NSTimeInterval) {
    let animation = CABasicAnimation(keyPath: "strokeEnd")

    animation.duration = duration

    animation.fromValue = 0
    animation.toValue = 1

    // Do a linear animation 
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)

    circleLayer.strokeEnd = 1.0

    // Do the actual animation
    circleLayer.addAnimation(animation, forKey: "animateCircle")
}

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

最佳答案

假设您的 View 中有一个名为 labelUILabel 属性;您可以在 layoutSubviews 方法中将 center 值设置为 View 的中心:

override func layoutSubviews() {
    super.layoutSubviews()

    label.sizeToFit()
    label.center = self.convertPoint(self.center, fromView: self.superview)
}

请注意,使用 Auto Layout 会容易得多,但您无法像上面那样更改任何框架或中心:

self.addConstraint(NSLayoutConstraint(
    item: label, 
    attribute: NSLayoutAttribute.CenterX, 
    relatedBy: NSLayoutRelation.Equal, 
    toItem: self, 
    attribute:  NSLayoutAttribute.CenterX, 
    multiplier: 1.0, constant: 0.0))

self.addConstraint(NSLayoutConstraint(
    item: label, 
    attribute: NSLayoutAttribute.CenterY, 
    relatedBy: NSLayoutRelation.Equal, 
    toItem: self, 
    attribute:  NSLayoutAttribute.CenterY, 
    multiplier: 1.0, constant: 0.0))

关于ios - 如何将文本居中放置在圆圈中间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31971092/

相关文章:

iphone - iPhone 中的自动滚动选框标签

uitableview - 如何将 UILabels 正确插入到每个 tebleview 单元格中

ios - 来自 CNContactStore 请求访问的错误 "A promise was finished incorrectly"

ios - 使用 Swift 4.1.2 编译的模块无法在 Swift 4.1.50 中导入 : Xcode 10 Error

ios - 在 UITableView 中滚动时移动 View

ios - 谷歌地图自动完成改变颜色

swift - 如何约束 View 中的元素?

ios - 使用 NSAttributedString 的 UILabel 的 NSForegroundColorAttributeName

ios - UITableViewController 由于单元格标识符而崩溃

ios - 如何检查父SCNNode是否包含子SCNNode