首先是懒加载了runLabel:
private lazy var runLabel : UILabel={
let label = UILabel()
label.sizeToFit()
label.font = UIFont(name: kMyFontName, size: kFontSize14)
label.textColor = UIColor.blackColor()
return label
}()
然后在viewDidLoad中实现addsubView方法:
/// 跑马灯
self.navigationItem.titleView?.addSubview(runLabel)
//设置label的原始位置
runLabel.frame.origin.x = kScreenWidth
UIView.beginAnimations(self.productName, context: nil)
UIView.setAnimationDuration(16)
UIView.setAnimationCurve(UIViewAnimationCurve.Linear)
UIView.setAnimationDelegate(self)
UIView.setAnimationRepeatCount(999999)
runLabel.frame.origin.x = -runLabel.frame.size.width
UIView .commitAnimations()
另外如果文字过长的话建议直接计算文字宽度(做个简单的分类即可)
extension String {
func getTitleW() -> CGFloat{
/// 计算文字宽度
var dict:[String:AnyObject] = [:]
dict[NSFontAttributeName] = UIFont(name: kMyFontName, size: kFontSize14)
return NSString(string: self).boundingRectWithSize(CGSizeMake(999, 14), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: dict, context: nil).size.width + 24
}
}