简单:swift 实现文本横向滚动,跑马灯效果
实现思路:UIScrollView上放UIlabel ,ScrollView.contentSize的宽和文本宽度一样,然后设置定时器循环调用改变选定的X坐标,到达最大宽度后,重复执行
1.定义如下三个:
privatevartimer: Timer? //消息滚动定时器
privatevarscrollContentOffsetX: CGFloat = 0//消息横向滚动位置记录
privatevarmessageW: CGFloat = 0//消息宽度
overridefuncviewDidLoad() {
super.viewDidLoad()
createUI()
}
funccreateUI() {
headView.addSubview(messageImageV)
headView.addSubview(messageScrollView)//可以滚动的视图
messageScrollView.addSubview(messageLb)//具体消息内容
//可以滚动视图
lazy var messageScrollView: UIScrollView = {
let view = UIScrollView()
view.showsVerticalScrollIndicator = false
view.showsHorizontalScrollIndicator = true
view.isScrollEnabled = false//可以滚动
return view
}()
//MARK: ---- 显示消息详情label
lazy var messageLb: UILabel = {
let view = UILabel()
view.text = ""
view.textColor = .hexColor("#FFFFFF")
view.textAlignment = .left
view.font = .font(size: 12, alias: .pfMedium)
return view
}()
2.拿到文本的地方,计算文本宽度(去掉里面的换行和空格) model.newsDescribe 就是拿到的文本
let firstMessage = model.newsDescribe.replacingOccurrences(of: " ", with: "")//处理换行
let setMessage = " " + firstMessage.replacingOccurrences(of: "\n", with: "")//处理换行
//计算文本宽度
let descWidth = setMessage.boundingRect(with: CGSize.init(width: CGFloat(MAXFLOAT), height: CGFloat(20)), options: .usesLineFragmentOrigin, attributes: [.font: UIFont.font(size: 12, alias: .pfMedium)], context: nil).size.width
print("文本宽度")
self.messageW = descWidth
self.messageLb.text = String(setMessage)
self.messageScrollView.contentSize = CGSize(width: descWidth, height: 20)
self.startTimer()
3.定时器方法处理
//MARK: ---- 开启定时器
private func startTimer() {
self.timer?.invalidate()
self.timer = nil
self.timer = Timer.scheduledTimer(timeInterval: 0.03, target: self, selector: #selector(timerSelector), userInfo: nil, repeats: true)
iflet `timer` = timer {
RunLoop.main.add(timer, forMode: .common)
}
}
//MARK: ---- 定时器调用
@objc private func timerSelector() {
ifmessageW < self.messageLb.frame.width - 10 {
scrollContentOffsetX = 0
messageScrollView.setContentOffset(CGPoint.init(x: 0, y: 0), animated: false)
return
}
ifmessageScrollView.contentOffset.x >= messageW {
scrollContentOffsetX = 0
messageScrollView.setContentOffset(CGPoint.init(x: 0, y: 0), animated: false)
}
scrollContentOffsetX += 1
messageScrollView.setContentOffset(CGPoint.init(x: scrollContentOffsetX, y: 0), animated: true)
}
posted on 2022-07-01 10:54 yucaijiang 阅读(852) 评论(0) 编辑 收藏 举报