UIPickerView使用

本文介绍了一个iOS应用中使用UIKit进行界面初始化的方法,并详细展示了如何利用UIPickerView实现一个选择年级的功能,包括创建工具栏、设置按钮及响应事件。

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

- (void)initUI
{
    UIToolbar * topView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
    [topView setBarStyle:UIBarStyleBlack];
    UIBarButtonItem * spaceButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self.superview action:@selector(saveGrade)];
    NSArray * buttons = [NSArray arrayWithObjects:spaceButton, doneButton, nil];
    [topView setItems:buttons];
    [self addSubview:topView];
    self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 30, 320, 245)];
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    self.pickerView.showsSelectionIndicator = YES;
    [self addSubview:self.pickerView];
    self.gradeList = [NSArray arrayWithObjects:@"一年级", @"二年级", @"三年级", @"四年级", @"五年级", @"六年级", @"初一", @"初二", @"初三", @"高一", @"高二", @"高三",@"大学", nil];
    [self.pickerView selectRow:5 inComponent:0 animated:YES];
}

//返回显示的列数。
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

//返回当前显示的行数。
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [self.gradeList count];
}

//设置当前行的内容,若没有内容则自动释放。
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [self.gradeList objectAtIndex:row];
}

//设置内容居中显示。
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel * label = [[[UILabel alloc] initWithFrame:CGRectMake(12, 0, [pickerView rowSizeForComponent:component].width - 12, [pickerView rowSizeForComponent:component].height)] autorelease];
    [label setText:[self.gradeList objectAtIndex:row]];
    label.backgroundColor = [UIColor clearColor];
    [label setTextAlignment:UITextAlignmentCenter];
    return label;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值