Iyy*_*avi 7 cocoa-touch objective-c ios swift
如何使用 NSTimer 在水平位置自动滚动 UIcollectionView
我正在处理我的项目源代码如下:
- (void)viewDidLoad {
[super viewDidLoad];
self.endPoint = CGPointMake(0, self.collectionView.frame.size.width);
self.scrollingPoint = CGPointMake(0, 0);
self.scrollingTimer = [NSTimer scheduledTimerWithTimeInterval:0.015 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}
- (void)onTimer {
self.collectionView.contentOffset = self.scrollingPoint;
if (CGPointEqualToPoint(self.scrollingPoint, self.endPoint)) {
[self.scrollingTimer invalidate];
}
self.scrollingPoint = CGPointMake(self.scrollingPoint.x+1, 0);
}
Run Code Online (Sandbox Code Playgroud)
尝试使用上面的代码,但对我不起作用。
斯威夫特 4.2
带有 Runloop 和 Timer 块。调整 0.015 和 0.25 值以匹配您所需的速度。
var carousalTimer: Timer?
var newOffsetX: CGFloat = 0.0
func startTimer() {
carousalTimer = Timer(fire: Date(), interval: 0.015, repeats: true) { (timer) in
let initailPoint = CGPoint(x: self.newOffsetX,y :0)
if __CGPointEqualToPoint(initailPoint, self.collectionView.contentOffset) {
if self.newOffsetX < self.collectionView.contentSize.width {
self.newOffsetX += 0.25
}
if self.newOffsetX > self.collectionView.contentSize.width - self.collectionView.frame.size.width {
self.newOffsetX = 0
}
self.collectionView.contentOffset = CGPoint(x: self.newOffsetX,y :0)
} else {
self.newOffsetX = self.collectionView.contentOffset.x
}
}
RunLoop.current.add(carousalTimer!, forMode: .common)
}
Run Code Online (Sandbox Code Playgroud)
// Swift-3
var timr=Timer()
var w:CGFloat=0.0
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
configAutoscrollTimer()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidAppear(true)
deconfigAutoscrollTimer()
}
func configAutoscrollTimer()
{
timr=Timer.scheduledTimer(timeInterval: 0.03, target: self, selector: #selector(dashboard_ViewController.autoScrollView), userInfo: nil, repeats: true)
}
func deconfigAutoscrollTimer()
{
timr.invalidate()
}
func onTimer()
{
autoScrollView()
}
func autoScrollView()
{
let initailPoint = CGPoint(x: w,y :0)
if __CGPointEqualToPoint(initailPoint, ticker.contentOffset)
{
if w<collection_view.contentSize.width
{
w += 0.5
}
else
{
w = -self.view.frame.size.width
}
let offsetPoint = CGPoint(x: w,y :0)
collection_view.contentOffset=offsetPoint
}
else
{
w=collection_view.contentOffset.x
}
}
Run Code Online (Sandbox Code Playgroud)
// 这很好用
| 归档时间: |
|
| 查看次数: |
11002 次 |
| 最近记录: |