UIAlertController
而不是UIPickerView
,这是有意为之的,因为它允许用户同时看到更多的选项,并利用iPad和更大的iPhone上可用的屏幕大小。此外,选择后的反馈是即时的,因为视图在选择后立即消失,Cancel
是一个标准动作,允许用户快速取消选择,并且如果只有几个选项就不需要用户滚动,这意味着只需要一次轻触就可以进行选择。
以下是我用来生成按钮和相应的UIAlertController
的代码:
if (self.question.placeholderText) {
[self.answerButton setTitle:NSLocalizedString(self.question.placeholderText, @"") forState:UIControlStateNormal];
} else {
[self.answerButton setTitle:NSLocalizedString(@"Please Select One", nil) forState:UIControlStateNormal];
}
[self.answerButton setTitle:[self paddedString:self.answerButton.titleLabel.text] forState:UIControlStateNormal];
self.answerButton.titleLabel.textAlignment = NSTextAlignmentLeft;
self.answerButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
self.answerButton.titleLabel.font = [UIFont appFont];
[self.answerButton setTitleColor:[UIColor appColor] forState:UIControlStateNormal];
[self.answerButton addTarget:self action:@selector(longListLabelTapped) forControlEvents:UIControlEventTouchUpInside];
self.answerButton.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.0001f];
self.answerButton.titleLabel.layer.borderColor = [UIColor appColor].CGColor;
self.answerButton.titleLabel.layer.borderWidth = 1.0f;
self.answerButton.titleLabel.layer.cornerRadius = 5.0f;
- (NSString *)paddedString:(NSString *)input {
//This adds some space around the button title just to make it look better
return [NSString stringWithFormat:@" %@ ", input];
}
UIAlertController
,您需要一个选项数组。_optionsController = [UIAlertController
alertControllerWithTitle:self.question.longListTitle
message:nil
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
}];
[_optionsController addAction:cancelAction];
for (NSString *optionName in self.question.possibleAnswers) {
UIAlertAction *action = [UIAlertAction actionWithTitle:optionName
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
// Do something with the selected answer
[self.answerButton setTitle:[self paddedString:optionName]
forState:UIControlStateNormal];
}];
[_optionsController addAction:action];
}