以编程方式为循环加载动画的 UILabel 添加约束
Posted
技术标签:
【中文标题】以编程方式为循环加载动画的 UILabel 添加约束【英文标题】:Programmatically adding constraints for a UILabel for a circular load animation 【发布时间】:2016-01-13 05:38:03 【问题描述】:我正在尝试以编程方式在使用Open Source software
创建的循环加载图像中添加label
。我面临的问题是我不知道如何constrain
标签使其包含在圆圈内。我正在尝试将CAShapeLayer
与UILabel
进行比较,但这不起作用,因为CAShapeLayer
不是Storyboard
提供的类型。有没有我应该遵循的建议修复?
let circlePathLayer = CAShapeLayer()
var circleRadius: CGFloat = 100.0
var circleCenter: CGPoint = CGPoint()
func displayStatus()
let statusLabel = UILabel(frame: CGRectMake(0, 0, 200, 21))
statusLabel.center = CGPointMake(160, 284)
statusLabel.textAlignment = NSTextAlignment.Center
statusLabel.textColor = UIColor.whiteColor()
statusLabel.text = "(Up)loading"
let horizontalConstraint = NSLayoutConstraint(item: statusLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: circlePathLayer, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0) //ERROR
self.addConstraint(horizontalConstraint)
let verticalConstraint = NSLayoutConstraint(item: statusLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: circlePathLayer, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0) //ERROR
self.addConstraint(verticalConstraint)
self.addSubview(statusLabel)
【问题讨论】:
【参考方案1】:删除此代码:
let horizontalConstraint = NSLayoutConstraint(item: statusLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: circlePathLayer, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0) //ERROR
self.addConstraint(horizontalConstraint)
let verticalConstraint = NSLayoutConstraint(item: statusLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: circlePathLayer, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0) //ERROR
self.addConstraint(verticalConstraint)
添加此代码:
目标 C:
- (void)layoutSubviews
[super layoutSubviews];
statusLabel.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds))
斯威夫特:
override func layoutSubviews()
super.layoutSubviews()
statusLabel.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidX(self.bounds))
【讨论】:
你有这个的 Swift 版本吗? 使用 Swift 代码更新。以上是关于以编程方式为循环加载动画的 UILabel 添加约束的主要内容,如果未能解决你的问题,请参考以下文章
以编程方式将 UILabel 添加到 CollectionViewCells