문제

I have a UIButton that is gray when the user enters a viewController. There is also a UITextView. If the user enters text into the UITextView, then the button should turn red, but if the text view is blank, the the button is gray. If was thinking of doing something like bellow, which does change the color to red if the user enters text, but if the user deletes the text, it stays red instead of going back to gray. Here is the code I am using:

- (void)textViewDidChange:(UITextView *)textView {

if (self.textView.text.length == 0) {
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithRed:193/255.5 green:193/255.0 blue:193/255.0 alpha:1.0];
}else{

    self.navigationItem.rightBarButtonItem.tintColor = [UIColor redColor];
}

if (self.titleView.text.length == 0) {
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithRed:193/255.5 green:193/255.0 blue:193/255.0 alpha:1.0];
}else{

    self.navigationItem.rightBarButtonItem.tintColor = [UIColor redColor];
}

NSLog(@"Typing has stopped");

}
도움이 되었습니까?

해결책

Use if (self.textView.text.length == 0) instead of checking if the text is null.

다른 팁

For Swift 3:

if (self.textView.text.characters.count == 0)

You could bind the button image to the text view value and then use a value transformer to put in different colored images depending on if there's input.

Code is for OSX but hopefully it's adaptable.

@implementation DBHasTextImageTransformer

- (id)init
{
  self = [super init];
  if (self) {
    // Initialization code here.
  }

  return self;
}


+ (Class)transformedValueClass
{
  return [NSImage class];
}


+ (BOOL)allowsReverseTransformation
{
  return NO;
}


- (id)transformedValue:(id)value
{

  if ((value == NULL) || [value isEqualToString:@""]) {

    return [NSImage imageNamed: @"NoTextImage"];

  } else {

    return [NSImage imageNamed: @"HasTextImage"];

  }

}


@end
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top