gpt4 book ai didi

ios - 通过 Donebutton 关闭 UIPickerView

转载 作者:行者123 更新时间:2023-11-28 22:27:21 25 4
gpt4 key购买 nike

我有这个代码。用于文本字段的 UIPickerView。
我想这样设计
当用户编辑UITextField时,显示UIPickerViewdonebutton
UIPickerView 通过按下 donebutton 关闭。

问题是 doneButton 没有显示。
所以,Picker无法关闭。

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource>

@property (weak, nonatomic) IBOutlet UITextField *textField1;
@property (weak, nonatomic) IBOutlet UITextField *textField2;

@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
{
UIPickerView *picker1;
NSString *pic1_str;
}
@synthesize textField1;
@synthesize textField2;

- (void)viewDidLoad
{
[super viewDidLoad];

textField1.delegate = self;

picker1 = [[UIPickerView alloc] init];
picker1.frame = CGRectMake(0, 460, 320, 216);
picker1.showsSelectionIndicator = YES;
picker1.delegate = self;
picker1.dataSource = self;
picker1.tag = 1;
[self.view addSubview:picker1];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
[self showPicker1];
return NO;
}

- (void)showPicker1 {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.2];
[UIView setAnimationDelegate:self];
picker1.frame = CGRectMake(0, 204, 320, 216);
[UIView commitAnimations];

if (!self.navigationItem.rightBarButtonItem) {
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(done:)];
[self.navigationItem setRightBarButtonItem:doneButton animated:YES];
}
}

- (void)done:(id)sender {
[self hidePicker];
[self.navigationItem setRightBarButtonItem:nil animated:YES];
}

- (void)hidePicker {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.2];
[UIView setAnimationDelegate:self];
picker1.frame = CGRectMake(0, 420, 320, 216);
[UIView commitAnimations];
}

关于如何修复它的任何想法?

最佳答案

您也可以通过设置 UITextField 对象的 inputView 来做到这一点:

- (BOOL) textFieldShouldBeginEditing:(UITextField *)textField
{
textField.inputView = _pickerView;
textField.inputAccessoryView = self.accessoryView_;

return YES;
}

属性 accessoryView_ 可以用以下实例化:

self.accessoryView_ = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, _pickerView.frame.size.width, 40)];

[(UIToolbar *) self.accessoryView_ setItems:@[
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissPicker)]
]];

在你的代码中的某个地方(viewDidLoad 是一个很好的地方)

dismissPicker 很简单

- (void) dismissPicker
{
[_textField resignFirstResponder];
}

当然,您必须使用属性或 ivar 保留对 textField 的引用

关于ios - 通过 Donebutton 关闭 UIPickerView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18530424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com