我想要一个 Edit barButtonItem,按下时我希望能够选择一个分段控件并编辑我选择的分段标题并保存它。这可能吗?
问问题
1639 次
1 回答
1
我花了一些时间来想出这个例子,但就是这样!!!
这是我的 UIViewController 头文件中的内容:
@interface optionsViewController : UIViewController <UIPopoverControllerDelegate, UITextFieldDelegate> {
IBOutlet UISegmentedControl * centerAreaSizeSelector;
// Added to support this example
UISegmentedControl * controlBeingEdited;
unsigned int segmentBeingEdited;
}
-(IBAction)centerAreaSizeSelector:(id)sender;
@end
显然,我的 UISegmented 控件及其操作项在 Interface Builder 中连接。
您必须为您的分段控件实施操作项,这是我的
-(IBAction)centerAreaSizeSelector:(id)sender{
// These are zero Based Reads from the selectors
unsigned char centerAreaSizeSelection = centerAreaSizeSelector.selectedSegmentIndex;
// Here we instantiate a NEW invisible UITextField to bring up the keyboard.
UITextField * textField = [[UITextField alloc] init];
[self.view addSubview:textField];
textField.hidden = YES;
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.text = [centerAreaSizeSelector titleForSegmentAtIndex:centerAreaSizeSelection];
textField.delegate = self;
[textField becomeFirstResponder];
// The below variable are defined globally to allow the keyboard delegate routines
// to know which segmented control and which item within the control to edit
// My design has multiple UISegmentedControls so this is needed for separation
controlBeingEdited = centerAreaSizeSelector; // of type UISegmentedControl
segmentBeingEdited = centerAreaSizeSelection; // of type unsigned int
}
实现如下 3 个 UITextFieldDelegate 方法如下
// Implement the keyboard delegate routines
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
[textField release];
controlBeingEdited = nil;
segmentBeingEdited = 0;
return YES;
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSString * theString = [textField.text stringByReplacingCharactersInRange:range withString:string];
[controlBeingEdited setTitle:theString forSegmentAtIndex:segmentBeingEdited];
return YES;
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
[controlBeingEdited setTitle:textField.text forSegmentAtIndex:segmentBeingEdited];
}
这实现了 UISegmentedControl 元素的逐键可见编辑。
注意:如果文本大于控件提供的空间,这绝不会实现可能需要的自动调整大小。
这也没有实现任何形式的可见光标或可见选择代码。
这将在字符串中的最后一个字符之后留下文本字段插入符号的位置。它会在编辑之前将当前 UISegmentedControl 的文本复制到不可见的文本字段中,这样您就不会丢失副本,尽管可以很容易地对其进行编辑以在编辑之前清除两者。
于 2012-06-12T03:08:57.473 回答