1、封装label
import UIKit
class MyFlashLabel: UIView {
var innerContainer: UIView
//计算text长度并返回
func evaluateContentWidth(text: String) -> CGFloat {
var height: CGFloat = 0.0
let options: NSStringDrawingOptions = NSStringDrawingOptions.UsesLineFragmentOrigin
if text.characters.count > 0 {
let attributedDic = [NSFontAttributeName : UIFont.systemFontOfSize(12.0)]
let size: CGSize = text.boundingRectWithSize(CGSizeMake(self.bounds.size.width - 20,CGFloat(MAXFLOAT)), options: options, attributes:attributedDic, context: nil).size
height = size.height
}
return height
}
init(frame: CGRect, text: String) {
self.innerContainer = UIView()
super.init(frame: frame)
self.innerContainer = UIView(frame: self.bounds)
self.innerContainer.backgroundColor = UIColor.clearColor()
self.clipsToBounds = true
self.backgroundColor = UIColor.yellowColor()
self.addSubview(self.innerContainer)
print(self.subviews.count)
self.flashAnimation(text)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 动画
func flashAnimation(text: String) {
self.innerContainer.layer.removeAnimationForKey("move")
let height: CGFloat = self.evaluateContentWidth(text)
let label1: UILabel = UILabel(frame: CGRectMake(10,0,self.bounds.size.width - 10,height))
label1.text = text
label1.numberOfLines = 0
label1.textColor = UIColor.greenColor()
label1.font = UIFont.systemFontOfSize(12.0)
label1.backgroundColor = UIColor.clearColor()
self.innerContainer.addSubview(label1)
if height > self.bounds.size.height {
let label2: UILabel = UILabel(frame: CGRectMake(10,height + 5,self.bounds.size.width - 10,height))
label2.text = text
label2.numberOfLines = 0
label2.backgroundColor = UIColor.clearColor()
label2.font = UIFont.systemFontOfSize(12.0)
label2.textColor = UIColor.greenColor()
self.innerContainer.addSubview(label2)
let moveAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position.y")
moveAnimation.keyTimes = [0.0,1.0]
moveAnimation.duration = Double(height)/5.0
moveAnimation.values = [0,-height - 5]
moveAnimation.repeatCount = MAXFLOAT
moveAnimation.timingFunction = CAMediaTimingFunction(name: "linear")
self.innerContainer.layer.addAnimation(moveAnimation, forKey: "move")
}
}
}
2、添加到指定控制器
let labelView: MyFlashLabel = MyFlashLabel(frame: CGRectMake(20, 100, 280, 100), text: "\n滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧\n滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧\n滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧滚动吧")
self.view.addSubview(labelView)