1

我正在尝试制作自定义 TextField (KSTextField)。我从 UITextField 继承了我的文本字段。正如您在下面看到的我的 KSTextField.h 文件。

#import <UIKit/UIKit.h>
#import <UIKit/UITextField.h>

@interface KSTextField : UITextField {}

@end

在我的 KSTextField.mi 中尝试设置一个虚拟文本属性。但它不起作用。super.text 使用错误吗?

我的主要目的是制作一个仅允许我的项目所需的大写字符的自定义 UITextField。

#import "KSTextField.h"

@implementation KSTextField

- (id)init {
    self = [super init];

    super.text = @"help";
    return self;
}

- (void)textFieldDidChangeForKS:(KSTextField *)textField {
    self.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
    NSString *textToUpper = [textField.text uppercaseString];
    [self setText:textToUpper];
}

@end

还有我的 ViewController.h 在下面

#import <UIKit/UIKit.h>
#import "KSTextField.h"

@interface ViewController : UIViewController 


@property (nonatomic, copy) IBOutlet KSTextField *txtKsName;


@end

这是我的 ViewController.m,我想设置我的 KSTextField.text

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.txtKsName = [[KSTextField alloc] init];

}

代表事件不能解决我的问题。因为我稍后会添加更多功能。这将是我的自定义文本字段,谢谢!

4

1 回答 1

2

答案是:你做错了!您不必子类化以仅允许大写字符。使用UITextFieldDelegate

http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html

使用该textField:shouldChangeCharactersInRange:replacementString:方法,您可以判断是否允许将键入的字符添加到框中。

尝试这样的事情:

- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
{
    NSCharacterSet *blockedCharacters = [[[NSCharacterSet uppercaseLetterCharacterSet] invertedSet] retain];
    return ([characters rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound);
}
于 2013-03-28T14:12:35.433 回答