我正在 SWIFT 中为 iOS8 创建一个应用程序,它要求用户通过按 UIButton 输入负号。我正在使用的键盘是DecimalPad,它没有该选项。我有多个按钮需要使用的文本字段。例如,如果选择了 UITextField 并且用户按下"-"按钮,则将在该文本字段中插入"-"。我在UIButton知道正在选择哪个UITextField时遇到问题。
任何帮助将不胜感激。
谢谢
@property (weak, nonatomic) IBOutlet UIButton *button;
@property (strong, nonatomic) UITextField *selectedTextField;
- (void) viewDidLoad{
[super viewDidLoad];
[self.button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
}
- (void) buttonTapped: (UIButton *) sender{
self.selectedTextField.text = [NSString stringWithFormat:@"-%@",self.selectedTextField.text];
}
//Make sure you set the delegate of every UITextField to this UIViewController.
//Also make sure you state that this UIViewController implements the UITextFieldDelegate protocol by inserting <UITextFieldDelegate> in the interface header.
-(void)textFieldDidBeginEditing:(UITextField *)sender{
self.selectedTextField = sender;
}
此解决方案利用insertText:
允许您在当前光标位置的任何位置插入"-"。注意:确保将UITextField
委托设置为自身,以利用textFieldDidBeginEditing:
和textFieldDidEndEditing:
委托方法。
class ViewController: UIViewController, UITextFieldDelegate {
var selectedTextField:UITextField?
@IBAction func negativeButtonPress(sender: UIButton) {
// If a text field stored in selectedTextField
// insert "-" at the cursor position
if let field:UITextField = selectedTextField {
field.insertText("-")
}
}
// Sets selectedTextField to the current text field
// when the text field begins editing
func textFieldDidBeginEditing(textField: UITextField) {
selectedTextField = textField
}
// Sets selectedTextField to the nil
// when the text field ends editing
func textFieldDidEndEditing(textField: UITextField) {
selectedTextField = nil
}
}