AJ學IOS 之微博項目實戰(11)發送微博自定義TextView實現帶佔位文字

AJ分享,必須精品java

 

一:效果

這裏寫圖片描述

二:代碼:

因爲系統自帶的UITextField:和UITextView:不能知足咱們的需求,因此咱們須要本身設計一個。markdown

UITextField:
1.文字永遠是一行,不能顯示多行文字
2.有placehoder屬性設置佔位文字
3.繼承自UIControl
4.監聽行爲
1> 設置代理
2> addTarget:action:forControlEvents:
3> 通知:UITextFieldTextDidChangeNotificationapp

UITextView:
1.能顯示任意行文字
2.不能設置佔位文字
3.繼承自UIScollView
4.監聽行爲
1> 設置代理
2> 通知:UITextViewTextDidChangeNotificationdom

NYTextView.h

//
// Created by apple on 14-10-20.
// Copyright (c) 2014年 heima. All rights reserved.
// 加強:帶有佔位文字

#import <UIKit/UIKit.h>

@interface NYTextView : UITextView
/** 佔位文字 */
@property (nonatomic, copy) NSString *placeholder;
/** 佔位文字的顏色 */
@property (nonatomic, strong) UIColor *placeholderColor;
@end

NYTextView.m

// Created by apple on 14-10-20.
// Copyright (c) 2014年 heima. All rights reserved.
//

#import "NYTextView.h"

@implementation NYTextView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // 不要設置本身的delegate爲本身
// self.delegate = self;

        // 通知
        // 當UITextView的文字發生改變時,UITextView本身會發出一個UITextViewTextDidChangeNotification通知
        [NYNotificationCenter addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
    }
    return self;
}


- (void)dealloc
{
    [NYNotificationCenter removeObserver:self];
}

/** * 監聽文字改變 */
- (void)textDidChange
{
    // 重繪(從新調用)
    [self setNeedsDisplay];
}

- (void)setPlaceholder:(NSString *)placeholder
{
    _placeholder = [placeholder copy];

    [self setNeedsDisplay];
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    _placeholderColor = placeholderColor;

    [self setNeedsDisplay];
}

- (void)setText:(NSString *)text
{
    [super setText:text];

    // setNeedsDisplay會在下一個消息循環時刻,調用drawRect:
    [self setNeedsDisplay];
}

- (void)setFont:(UIFont *)font
{
    [super setFont:font];

    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
// [NYRandomColor set];
// UIRectFill(CGRectMake(20, 20, 30, 30));
    // 若是有輸入文字,就直接返回,不畫佔位文字
    if (self.hasText) return;

    // 文字屬性
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = self.font;
    attrs[NSForegroundColorAttributeName] = self.placeholderColor?self.placeholderColor:[UIColor grayColor];
    // 畫文字
// [self.placeholder drawAtPoint:CGPointMake(5, 8) withAttributes:attrs];
    CGFloat x = 5;
    CGFloat w = rect.size.width - 2 * x;
    CGFloat y = 8;
    CGFloat h = rect.size.height - 2 * y;
    CGRect placeholderRect = CGRectMake(x, y, w, h);
    [self.placeholder drawInRect:placeholderRect withAttributes:attrs];
}

@end
相關文章
相關標籤/搜索