【问题标题】:I cannot set text of my Custom Text Field我无法设置自定义文本字段的文本
【发布时间】:2013-03-28 14:10:40
【问题描述】:

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

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

@interface KSTextField : UITextField {}

@end

在我的 KSTextField.m 中,我尝试设置一个虚拟文本属性。但它不起作用。 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

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

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

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

}

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

【问题讨论】:

    标签: ios objective-c uitextfield


    【解决方案1】:

    答案是:你做错了!您不必子类化以仅允许大写字符。使用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);
    }
    

    【讨论】:

    • 我应该在哪里使用它?在我的 ViewController.m 上?我做了子类,因为我的一些文本输入只需要允许大写。不仅如此。也不是所有人。
    • 另外,在我的 KSTextField.m 中,我尝试设置一个虚拟文本属性,如您所见代码。但它不起作用。 super.text 的用法错了吗?
    • 有很多关于使用UITextViewDelegate 的资源比我能解释得更好,例如this。我肯定会使用委托而不是子类化,因为它更容易。
    • 我想要一个子类的原因是我可能会在我的类中添加更多的特性/行为,而不是在我的项目中使用 UITextfield,我想使用我自己的类来防止代码重复我添加的每个 UITextbox .. 所以创建子类仍然是错误的方法??
    • 您可以对任意数量的UITextFieldss 使用相同的委托,因此如果验证输入是您唯一关心的问题,那么是的,子类化是错误的方法。
    猜你喜欢
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 2014-12-23
    • 2016-01-28
    • 1970-01-01
    • 2021-07-12
    • 2019-01-31
    相关资源
    最近更新 更多