IOS开发基础UIPickerView循环显示

本文介绍了如何通过扩大UIPickerView显示范围并利用取余数来实现数据的循环显示,主要涉及设置数据源和代理方法,以及关键的滚轴滚动回调处理,确保滚轴始终显示在中间位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文适合对UIPickerView已经有一定了解的读者阅读。


核心思想是:整数倍扩大UIPickerView的显示区域范围,且显示的数据索引通过取余数获得。

下面是实现代码:

1.ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UIPickerViewDataSource, UIPickerViewDelegate>

@property(strong, nonatomic)UIPickerView *myPickerView;

//显示的实际数据

@property(strong, nonatomic)NSArray *data;

@end



2.ViewController.m

#import "ViewController.h"

#define WIDTH self.view.frame.size.width

#define HEIGHT self.view.frame.size.height

//倍数

#define MULTIPLE 51

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

self.myPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(WIDTH*0.40, HEIGHT*0.20, WIDTH*0.20, HEIGHT*0.1)];

//添加代理

self.myPickerView.delegate = self;

self.myPickerView.dataSource = self;

[self.view addSubview:self.myPickerView];

//实际显示数据

NSArray *arr = @[@"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"10"];

self.data = arr;

//让滚轴显示指定的位置, 中间的位置

[self.myPickerView selectRow:MULTIPLE/2*self.data.count inComponent:0 animated:NO];

}


#pragma mark 实现UIPickerViewDataSource协议

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{

return 1;

}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{

//使UIPickerView显示的范围扩大MULTIPLE

return self.data.count*MULTIPLE;

}


#pragma mark 实现UIPickerViewDelegate的代理方法

//设置当前componentrow显示的标题

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{

//通过取余数使得显示的实际数据索引被限定在一定范围

return self.data[row % self.data.count];

}

//核心部分,当滚轴滚动超出中间范围时返回回来

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{

//中间位置的相对长度

NSInteger length = MULTIPLE/2 * self.data.count;

//返回到中间位置

[self.myPickerView selectRow:row%self.data.count + length inComponent:0 animated:NO];

// NSLog(@"%ld", row%self.data.count + length);

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值