UITextView文本颜色更改问题

时间:2015-09-04 12:11:06

标签: ios uitextfield uicolor

我是iOS开发的新手。现在我正在制作一个UITextView Clickable。现在我可以点击UITextView。如果选中它并且未选择为黑色,我需要将文本更改为红色。

现在我的代码正常工作(每次我们点击UITextView更改颜色时都会出现这个功能)但是文字颜色没有变化(有时它有时不会改变)这里是我的代码,

//Code to make it clickable
UIGestureRecognizer *tapGesture1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
[Q1TextView addGestureRecognizer: tapGesture1];

//Function to handleTap
- (void) handleTapGesture: (UIGestureRecognizer*) recognizer{
    switch (recognizer.view.tag) {
        case 1:
            if (tv.textColor == [UIColor redColor]) {
                  NSLog(@"Red -> Black");
                  [Q1TextView setTextColor:[UIColor blackColor]];
            }
            else{
                 NSLog(@"Black -> Red");
                 [Q1TextView setTextColor:[UIColor redColor]];
            }
            break;
        default:

            break;
    }
    [self becomeFirstResponder];
}

我的日志就是这样,

Black -> Red
Red -> Black
Black -> Red
Red -> Black
Black -> Red
Red -> Black

3 个答案:

答案 0 :(得分:2)

为什么在可以使用o UITextView委托方法时实现点按手势。

在你的.m文件中写下这些

@interface myClass ()<UITextViewDelegate>


-(void)viewDidLoad{
  myTextview.delegate = self;
}
-(void)textViewDidBeginEditing:(UITextView *)textView{
textView.textColor = [UIColor redColor];
}
-(void)textViewDidEndEditing:(UITextView *)textView{
textView.textColor = [UIColor blackColor];
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if([text isEqualToString:@"\n"]){
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

答案 1 :(得分:0)

而不是切换案例使用tag

UITextView属性

viewDidLoad()设置Q1TextView.tag = 100

- (void) handleTapGesture: (UIGestureRecognizer*) recognizer{
    if (recognizer.view == Q1TextView) {

        if (Q1TextView.tag == 100) {
            Q1TextView.textColor = [UIColor redColor];
            Q1TextView.tag = 200;
        }
        else if (Q1TextView.tag == 200){
            Q1TextView.textColor = [UIColor blackColor];
            Q1TextView.tag = 100;
        }
    }
 [self becomeFirstResponder];
}

答案 2 :(得分:0)

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:touch.view];
    if ([[touch.view class] isSubclassOfClass:[UITextView class]]) {
        //Set Red color
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:touch.view];
    if ([[touch.view class] isSubclassOfClass:[UITextView class]]) {
        //Set Black color
    }
}