• 用UITextView模拟UITextField的placeHolder


    用UITextView模拟UITextField的placeHolder

    效果:

    源码:

    //
    //  ViewController.m
    //  TextView
    //
    //  Created by YouXianMing on 14/12/18.
    //  Copyright (c) 2014年 YouXianMing. All rights reserved.
    //
    
    #import "ViewController.h"
    
    static NSString *placeHolderStr = @"User Name";
    
    @interface ViewController ()<UITextViewDelegate>
    
    @property (nonatomic, strong) UITextView  *textView;
    @property (nonatomic, strong) UIButton    *button;
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        // 反应的按钮
        self.button = [[UIButton alloc] initWithFrame:self.view.bounds];
        [self.button addTarget:self
                        action:@selector(buttonEvent)
              forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.button];
        
        // textView
        self.textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 20, 320, 200)];
        self.textView.layer.borderWidth = 1.f;
        self.textView.layer.borderColor = [UIColor grayColor].CGColor;
        self.textView.delegate  = self;
        self.textView.text      = placeHolderStr;
        self.textView.font      = [UIFont systemFontOfSize:20.f];
        self.textView.textColor = [UIColor grayColor];
        [self.view addSubview:self.textView];
    }
    
    #pragma mark - 代理方法
    - (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
        // 设置编辑状态文字颜色
        textView.textColor = [UIColor blackColor];
        
        // 如果文字为placeHolder文字
        if ([textView.text isEqualToString:placeHolderStr]) {
            textView.text      = @"";
        }
        
        return YES;
    }
    - (BOOL)textViewShouldEndEditing:(UITextView *)textView {
        
        // 如果长度为0,则显示placeHolder文字
        if (textView.text.length == 0) {
            textView.text = placeHolderStr;
            textView.textColor = [UIColor grayColor];
        }
        
        return YES;
    }
    
    /**
     *  反应的按钮
     */
    - (void)buttonEvent {
        [self.textView resignFirstResponder];
    }
    
    @end

    核心代码:

  • 相关阅读:
    C++入门经典-例3.4-根据成绩划分等级
    C++入门经典-例3.3-if-else语句的奇偶性判别
    C++入门经典-例3.2-根据分数判断是否优秀
    C++入门经典-例3.1-判断输入的数字是否为奇数
    C++入门经典-例2.17强制类型转换
    C++入门经典-例2.16-隐式类型转换
    C++入门经典-例2.15-逗号表达式的应用
    C++入门经典-例2.14-使用移位运算
    C++入门经典-例2.13-左移运算
    Spring之Bean管理------注解方式
  • 原文地址:https://www.cnblogs.com/YouXianMing/p/4172066.html
Copyright © 2020-2023  润新知