我希望用户能够更改按钮的标题,这是我打算做的硬编码示例:
[myButton setTitle:@"B" forState:UIControlStateNormal];
但是,我宁愿用UIPicker提示用户,并允许用户从多个选项中进行选择以更改标题。
- (IBAction)handleLongPress:(UILongPressGestureRecognizer *)sender {
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(handleLongPress:)];
lpgr.minimumPressDuration = 1.0;
if ([sender.view isKindOfClass:[UIButton class]]) {
NSLog(@"user has clicked the button%@", sender.view);
UIButton *myButton = (UIButton *)sender.view;
UIPickerView *picker = [[UIPickerView alloc] init];
myButton.titleLabel = picker;
}
}
此时我看到错误*assignment to readonly property
是否可以将UIPickerView与UIButton的setTitle属性结合使用?如果是这样,这是如何实现的?
答案 0 :(得分:0)
错误很明显:
titleLabel是UIButton类的UILabel属性,它是只读的(不能将其设置为其他值)。您需要使用其标签的文本属性:
myButton.titleLabel.text = @"some text";
而不是:
myButton.titleLabel = picker;
或
myButton.titleLabel.text = picker;
因为picker不是NSString对象。
让我在一分钟内解释如何实现这个......
在View Controller类中,创建一个属性(我建议在私有界面中执行),并实现UIPickerViewDataSource,UIPickerViewDelegate协议:
@interface PPMyViewController () <UIPickerViewDataSource, UIPickerViewDelegate>
@property (nonatomic, strong) UIPickerView *pickerView;
@end
现在,对pickerView属性使用lazy instantiation:
- (UIPickerView *)pickerView
{
if (!_pickerView)
{
_pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
_pickerView.dataSource = self;
_pickerView.delegate = self;
}
return _pickerView;
}
Make sure you add to the main view, you can do it in the viewDidLoad method:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view addSubview:self.pickerView];
}
And implement most of the 2 protocols methods:
#pragma mark - UIPickerViewDataSource Methods
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return 10;
}
#pragma mark - UIPickerViewDelegate Methods
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component;
{
return 200;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
return 50;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [NSString stringWithFormat:@"row %d", row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSLog(@"Row %d selected", row);
// myButton.titleLabel.text = @"text you need depending on row selection";
}
请注意,我的代码会始终在底部显示UIPickerView。您可以根据需要隐藏/取消隐藏它。或者更好的是,使用动画将其定位在屏幕外而不是隐藏。
答案 1 :(得分:0)
你不能像你想的那样做。您需要做的是听取用户点击按钮,然后向用户显示一个选择器。
有一些开源控件可以简化此操作,例如ActionSheetPicker。