首先是懶加載了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中實現(xiàn)addsubView方法:
/// 跑馬燈
self.navigationItem.titleView?.addSubview(runLabel)
//設(shè)置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
}
}