我想要一个Edit barButtonItem,当按下时我希望能够选择一个分段控件并编辑我选择的段标题并保存它。这可能吗?
答案 0 :(得分: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元素的逐个键可见编辑。
注意: 如果文本大于控件提供的空间,则不会以任何方式实现自动调整大小。
这也没有实现任何形式的可见光标或可见选择代码。
这将在字符串中的最后一个字符后面留下textfield插入位置。它会在编辑之前将当前的UISegmentedControl文本复制到不可见的文本字段中,这样您就不会丢失副本,尽管可以在编辑之前轻松编辑它们以清除它们。