我尝试创建可用作进度条或类似内容的自定义UIView
(@IBDesignable
与IBInspectable
s)。我希望在此视图中居中(主要是X轴,但现在也是Y)UILabel
。
private func addLabel()
{
let label = UILabel(frame: CGRectMake(0, 0, self.frame.width / 4, self.frame.height / 4))
label.center = self.center
label.textAlignment = .Center
label.text = "5"
//Color just to see the whole label
label.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.5)
self.addSubview(label)
}
在Interfacebuilder中,标签中心很好:
但是,在我的设备(iPhone 5S)上运行时,标签会略微向右对齐(下图)。我尝试了不同的方法(比如制作标签框架self.frame
),但它仍未正确居中。我错过了什么?
override func drawRect(rect: CGRect) {
// Drawing code
let center = CGPoint(x:bounds.width/2, y: bounds.height)
let radius: CGFloat = max(bounds.width, bounds.height)
let startAngle: CGFloat = π
let endAngle: CGFloat = 2 * π
path = UIBezierPath(arcCenter: center, radius: radius / 2 - arcWidth / 2, startAngle: startAngle, endAngle: endAngle, clockwise: true)
path.lineWidth = arcWidth
arcBackgroundColor.setStroke()
path.stroke()
self.addLayer()
}
private func addLayer()
{
progressLayer = CAShapeLayer()
progressLayer.path = self.path.CGPath
progressLayer.strokeColor = self.progressColor.CGColor
progressLayer.fillColor = UIColor.clearColor().CGColor
progressLayer.lineWidth = self.arcWidth
if animatesOnDraw && progress > 0 {
self.layer.addSublayer(progressLayer)
self.animateProgress(0)
} else {
progressLayer.strokeEnd = CGFloat(self.progress / self.maxValue)
progressLayer.opacity = Float(self.progressStrokeEndValue)
self.layer.addSublayer(progressLayer)
}
addLabel() //as shown above
}
答案 0 :(得分:2)
问题是const Foxx = require('org/arangodb/foxx');
const TestMessage = Foxx.Model.extends({
schema: {/* ... */}
});
,因为标签的中心和超视图的中心位于不同的坐标系中,因此它们可能不同。改为使用
label.center = self.center
答案 1 :(得分:0)
试试这个:
self.label.center = view.center
答案 2 :(得分:0)
以编程方式添加UILabel并从
修改UILabel帧let label = UILabel(frame: CGRectMake(0, 0, self.frame.width / 4, self.frame.height / 4))
要
let label = UILabel(frame: CGRectMake(self.frame.width/2 - (self.frame.height/4)/2, 0, self.frame.width / 4, self.frame.height / 4))
<强> ELSE 强>
实施Autolayout
答案 3 :(得分:0)
可能的解决方案是: -
@IBOutlet customView : UIView!
//Let customView be the outlet of your custom view
func addLabel () {
let CenterY = customView.center.y
let CenterX = customView.center.x
let heightOfCustom = customView.frame.size.height
let widthOfCustom = customView.frame.size.width
// If you want a label with height and width 1/4th of the width of the custom view
let label = UILabel(frame : CGRectMake(CenterX - widthOfCustom/8, CenterY - heightOfCustom/8, widthOfCustom/4, heightOfCustom/4))
label.text = "5"
label.textAlignment = .Center
label.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.5)
self.addSubview(label)
}