<pre>
/// 滚动label
class USTradeScrollLabelView: USBaseView {
fileprivate let scrollLabel: UILabel = UILabel()
var scrollText: String = ""
fileprivate var rectMark1: CGRect = CGRect.zero
fileprivate var rectMark2: CGRect = CGRect.zero
fileprivate var arrLabel: [UILabel] = []
var timeInterval: TimeInterval = 0.0
var isStop: Bool = false
init(info: String, frame: CGRect) {
super.init(frame: frame)
// self.scrollText = info
self.scrollText = info
self.setupUI()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI() {
// super.setup()
self.scrollText = " \(self.scrollText) "
self.timeInterval = self.displayDurationForString(self.scrollText)
self.clipsToBounds = true
self.scrollLabel.us.customize { (view) in
view.text = self.scrollText
view.font = USFont.t05.font
view.us.handleTheme {
view.textColor = USColor.c301.color
}
}
let sizeOfText = self.scrollLabel.sizeThatFits(CGSize.zero)
self.rectMark1 = CGRect(x: 0, y: 0, width: sizeOfText.width, height: self.bounds.size.height)
self.rectMark2 = CGRect(x: self.rectMark1.origin.x + self.rectMark1.size.width, y: 0, width: sizeOfText.width, height: self.bounds.size.height)
self.scrollLabel.frame = self.rectMark1
self.addSubview(self.scrollLabel)
self.arrLabel.append(self.scrollLabel)
let useReserve = sizeOfText.width > self.frame.size.width ? true: false
if useReserve {
let reserveTextLabel = UILabel(frame: self.rectMark2)
reserveTextLabel.us.customize({ (view) in
view.text = self.scrollText
view.font = USFont.t05.font
view.us.handleTheme {
view.textColor = USColor.c301.color
}
self.addSubview(view)
self.arrLabel.append(reserveTextLabel)
// label滚动
self.scrollLabelIfNeeded()
})
}
}
fileprivate func scrollLabelIfNeeded() {
if !self.isStop {
let label1 = self.arrLabel[0]
let label2 = self.arrLabel[1]
UIView.transition(with: self, duration: self.timeInterval, options: [.curveLinear], animations: {
label1.frame = CGRect(x: -self.rectMark1.size.width, y: 0, width: self.rectMark1.size.width, height: self.rectMark1.size.height)
label2.frame = CGRect(x: label1.frame.origin.x + label1.frame.size.width, y: 0, width: label1.frame.size.width, height: label1.frame.size.height)
}, completion: { [weak self](finished) in
guard let `self` = self else {
return
}
label1.frame = self.rectMark2
label2.frame = self.rectMark1
self.arrLabel[0] = label2
self.arrLabel[1] = label1
self.scrollLabelIfNeeded()
})
}
}
fileprivate func displayDurationForString(_ string: String) -> TimeInterval {
let inter: TimeInterval = Double(string.characters.count / 3)
return inter
}
func start() {
self.isStop = false
let label1 = self.arrLabel[0]
let label2 = self.arrLabel[1]
label1.frame = self.rectMark2
label2.frame = self.rectMark1
self.arrLabel[0] = label2
self.arrLabel[1] = label1
self.scrollLabelIfNeeded()
}
func stop() {
self.isStop = true
}
}
</pre>
网友评论