如何在创建文本时才显示UI按钮?

时间:2014-03-21 17:08:33

标签: ios iphone objective-c

我正在制作文字游戏,我已经调用了自定义键盘textfield _textbox

我已经放了一个代表“清晰书面文字”的x按钮,我只需要在用户在文本字段中输入字母时显示它!

信件被清除后消失!

代码:

- (IBAction)btnclear:(id)sender {
NSString *oldString = _textbox.text;
NSString *newString;
newString = [oldString substringFromIndex: _textbox.text.length];
[_textbox setText:newString];

} 

图像在按钮上!

5 个答案:

答案 0 :(得分:1)

如果您使用的是UITextField,则可以使用标准清除按钮:

_textbox.clearButtonMode = UITextFieldViewModeWhileEditing;

如果您想要按钮的自定义外观,可以使用rightView和rightViewMode为您管理状态。

答案 1 :(得分:1)

使用以下代码,它使用UITextFieldTextDidChangeNotification通知,每次更改文本字段中的文本时都会调用该通知,并根据输入文本隐藏或显示按钮。

    - (void) viewDidLoad
    {
        [super viewDidLoad];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextFieldTextDidChangeNotification object: _textbox];
    }

    - (void) textDidChange:(NSNotification *)notification
    {
        UITextField *tf = (UITextField*)notification.object;
       _button.hidden = (tf.text.length == 0);
    }

    - (void)dealloc
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object: _textbox];
    }

答案 2 :(得分:0)

使用"hidden"的属性UIButton,您可以将其隐藏

检查textView上是否有文字,然后隐藏按钮

答案 3 :(得分:0)

使用UITextFielDelegate方法

 - (void)textFieldDidEndEditing:(UITextField *)textField
    {

    if(textField.text.length==0){
        textXclear.hidden = NO;
       }else{
        textXclear.hidden = YES;
      }
    }

答案 4 :(得分:0)

有两种方法,隐藏的意思是不可见或只是禁用?

如果不可见,请使用button.hidden属性。对于已禁用(意味着无法触及),请使用button.enabled属性。

至于文本字段,您可以执行以下操作:

if ([textfield.text length] > 0) {...} else {...}

//额外的东西和建议 此外,如果您使用文本字段中的文本添加到其他视图(例如其添加项目屏幕),则必须创建关于添加项目的@property。然后你可以,而不是前面提到的写代码,如.m:

if (self.aProperty != nil) {
    button.hidden = NO;
} else {
    button.hidden = YES; 

您必须在.h文件中声明该属性:

@property (nonatomic, strong) ObjectYouAreUsing *aProperty;

这可能是它无法工作的原因,但是使用NSObject子类创建新文件。这将是ObjectYouAreUsing。

这样您就可以访问正在使用的纯对象,只需将其导入到您需要的地方即可。此外,如果用户要关闭屏幕,则可以编写initWithCoder方法。