iphone - 使用 UIPickerView 而不是 UITextView

标签 iphone objective-c ios cocoa-touch

我确定这里的某个地方是解决方案,但我已经搜索了很长时间但没有找到任何东西

所以我的设置: .h

IBOutlet UITextField *valueOne;
IBOutlet UITextField *valueTwo;
    IBOutlet UILabel *total; 


- (IBAction)Lange;
@property (nonatomic, retain) UITextField *valueOne;
@property (nonatomic, retain) UITextField *valueTwo;

.m

- (IBAction)Lange{
    float f = arc4random_uniform(3) ;   
    float x = ([valueOne.text floatValue]-1.5)/1.5;
    float c = (5+[valueTwo.text floatValue])/2;
    float o = (x+c)/2+f;

    total.text = [[NSString alloc]initWithFormat:@"%.fcm", o]; 

}

我的问题:我正在搜索向我展示如何使用 pickerview 的代码/指南,我的意思是: 1. 用户在文本字段中输入 ValueOne。 2. 用户选择 4 个选项之一,即 ValueTwo(在 .m-> float c valueTwo.text 中,应填写我要设置的 4 个变量之一)。 那么我怎样才能获得带有预设变量的 pickerview 而用户只需要选择它呢?

如果有任何不清楚的地方,请随时发表评论。

编辑:我希望隐藏键盘并显示 pickerview,并且 pickerview 应该只在单击文本字段 valueTwo 时显示。

最佳答案

绝对是以上两个答案的组合。

首先,设置您的类以符合 UITextFieldDelegateUIPickerViewDelegate 协议(protocol):

@interface MyViewController : UIViewController <UITextFieldDelegate,
    UIPickerViewDelegate, UIPickerViewDataSource>
...
@end

接下来,声明项目数组和选择器 View 的属性。
然后您可以在代码中(或在 Nib 中)创建您的选择器 View 。无论哪种情况,请确保将选择器的 delegatedatasource 属性设置为 View Controller 。

将要修改的文本域的delegate属性设置为self,然后实现这个方法:

- (void)textFieldShouldBeginEditing:(UITextField *)textfield {
  [self presentPicker];
  return NO;
}

向@DavidH 致敬

您可以像这样定义选择器方法:

- (void)presentPicker {
  UIPickerView *picker = [[UIPickerView alloc] initWithFrame:SOME_FRAME_HERE];
  picker.delegate = self;
  picker.dataSource = self;

  // TODO: animate this on screen
  [self.view addSubview picker];
}

最后,您必须在这些协议(protocol)中实现必要的方法:

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
  return self.items.count;  //where items is your array of items
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row inComponent:(NSInteger)component {
  return [self.items objectAtIndex:row];
}

查看 UIPickerViewDelegate 协议(protocol)的方法,了解您将如何响应用户选择并关闭选择器。

作为无耻的 self 推销,我最近在 NSScreencast 上发布了一集在 how to build a custom picker view component这包括调暗它背后的 View ,在屏幕上和屏幕外设置动画,以及为“完成”和“取消”按钮添加工具栏。我在这里只提到这一点,因为它与您尝试做的事情直接相关。

希望这对您有所帮助!

关于iphone - 使用 UIPickerView 而不是 UITextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11600945/

相关文章:

iphone - 如何从 iPhone 中的地址查找纬度和经度

iphone - 将图像添加到 HTML 字符串 iphone

ios - 如何在 Objective C 中将数组数据从 iPhone 传递到 Apple Watch

ios - IBInspectable 和协议(protocol)

ios - 在某些 iOS 事件中暂停 Admob Interstitial

iphone - URLWithString 对于资源路径返回 nil - iphone

iphone - 如何在没有任何透明/淡入淡出效果的情况下执行 kCATransitionPush 动画

ios - 将 NSMutableArray 保存到文件

ios - Apple iOS App 图标标题 : maximum length?

ios - 在 initWithCoder : what are the keys in the NSCoder (a UINibDecoder)?(用于 UIImageView)