我正在SWIFT中为iOS8创建一个应用程序,要求用户通过按UIButton输入否定符号。我使用的键盘是DecimalPad,它没有这个选项。我有多个按钮需要使用的文本字段。例如,如果选择了UITextField并且用户按下“ - ”按钮,则会在该文本字段中插入“ - ”。我在UIButton知道哪个UITextField被选中时遇到了麻烦。
任何帮助都将不胜感激。
由于
答案 0 :(得分:0)
@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;
}
答案 1 :(得分:0)
此解决方案利用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
}
}