UICollectionView 实现,自动滚动、一屏横向显示3个view

前言

实现UICollectionView的自动滚动,以及一屏下,中间显示一个view,两边显示半个view的效果,
如图:

图片描述

自动滚动实现逻辑

自动滚动是使用Timer实现,每个一段时间让UICollectionView自动滚动下即可。

  • 定义一个Timer
//自动滚动计时器
var autoScrollTimer:Timer?
  • 定义一个下标,记录UICollectionView的下标
var index: Int = 0
  • 启动一个定时器
func startTimer() {
        //设置一个定时器,每三秒钟滚动一次
        autoScrollTimer = Timer.scheduledTimer(timeInterval: 3, target: self,
                                               selector: #selector(UICollectionViewTypeOneController.scroll),
                                               userInfo: nil, repeats: true)
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
很高兴为您解答这个问题!以下是一个简单的 Vue 实现文字公告自动横向循环滚动的 demo: ```html <template> <div class="notice"> <div class="notice-content" ref="noticeContent"> <div class="notice-item" v-for="(item, index) in noticeList" :key="index">{{ item }}</div> </div> </div> </template> <script> export default { data() { return { noticeList: ["这是第一条公告", "这是第二条公告", "这是第三条公告"], timer: null, speed: 50, step: 1, offset: 0, itemWidth: 0, containerWidth: 0, }; }, mounted() { this.itemWidth = this.$refs.noticeContent.querySelector(".notice-item").offsetWidth; this.containerWidth = this.$refs.noticeContent.offsetWidth; this.startScroll(); }, methods: { startScroll() { this.timer = setInterval(() => { this.offset += this.step; if (this.offset >= this.itemWidth) { this.offset = 0; this.noticeList.push(this.noticeList.shift()); } this.$refs.noticeContent.style.transform = `translateX(-${this.offset}px)`; }, this.speed); }, }, beforeDestroy() { clearInterval(this.timer); }, }; </script> <style scoped> .notice { width: 100%; overflow: hidden; white-space: nowrap; } .notice-content { display: inline-block; } .notice-item { display: inline-block; margin-right: 20px; } </style> ``` 在这个 demo 中,我们首先在模板中定义了一个容器,用来包裹公告内容。然后,我们在 `mounted` 钩子中获取了公告项的宽度和容器的宽度,以便后面计算滚动距离。接着,我们定义了一个 `startScroll` 方法,用来启动滚动。在这个方法中,我们使用了 `setInterval` 定时器来不断更新公告的位置,直到公告滚动到末尾时,将第一条公告移到最后,然后重新开始滚动。最后,我们在 `beforeDestroy` 钩子中清除了定时器,以防止内存泄漏。 希望这个 demo 能够帮助您实现文字公告自动横向循环滚动

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值