在使用textView的時(shí)候,我們?nèi)绻M鼡碛衪extField的占位文字的功能,就要自定義了。

下面給出具體的代碼:
(后面有注意點(diǎn)講解)
//.h文件#import <UIKit/UIKit.h>@interface XYLPlaceHodlerTextView : UITextView/**placeholder占位文字*/@PRoperty (nonatomic, copy) NSString *placeholder;/**placeholderColor占位文字顏色*/@property (nonatomic, strong) UIColor *placeholderColor;@end// .m文件#import "XYLPlaceHodlerTextView.h"@interface XYLPlaceHodlerTextView()/**UILabel*/@property (nonatomic, strong) UILabel *placeholderLabel;@end@implementation XYLPlaceHodlerTextView/** * 懶加載屬性,并設(shè)置屬性的值 */-(UILabel *)placeholderLabel{ if (!_placeholderLabel) { UILabel *label = [[UILabel alloc]init]; label.font = [UIFont systemFontOfSize:14]; label.textColor = [UIColor grayColor]; label.numberOfLines = 0; self.placeholderLabel = label; } return self.placeholderLabel;}/** * 設(shè)置自己的屬性 */-(instancetype)initWithFrame:(CGRect)frame{ if (self = [super initWithFrame:frame]) { self.alwaysBounceVertical = YES; self.textColor = [UIColor blackColor]; [XYLNotificationCenter addObserver:self selector:@selector(texting) name:UITextViewTextDidChangeNotification object:self]; } return self;}/** * 監(jiān)聽(tīng)有文字輸入 */-(void)texting{ [self setPlaceholderTextShow];}/** * 設(shè)置占位文字的顯示 */-(void)setPlaceholderTextShow{ self.placeholderLabel.hidden = self.hasText;}-(void)layoutSubviews{ [super layoutSubviews]; self.placeholderLabel.x = 4; self.placeholderLabel.y = 8; self.placeholderLabel.width = self.width - 2 * self.placeholderLabel.x; [self.placeholderLabel sizeToFit];//這一步很重要,不能遺忘}-(void)setPlaceholder:(NSString *)placeholder{// _placeholder = placeholder;//此句的意義何在? self.placeholderLabel.text = placeholder; [self setNeedsLayout];}-(void)setPlaceholderColor:(UIColor *)placeholderColor{ self.placeholderLabel.textColor = placeholderColor; [self setNeedsLayout];}-(void)setFont:(UIFont *)font{ [super setFont:font]; self.placeholderLabel.font = font; [self setNeedsLayout];}-(void)setText:(NSString *)text{ [super setText:text]; [self setPlaceholderTextShow];}-(void)setAttributedText:(NSAttributedString *)attributedText{ [super setAttributedText:attributedText]; [self setPlaceholderTextShow];}@end注意點(diǎn):
界面顯示步驟是先調(diào)用layoutSubviews將所有子控件的位置frame設(shè)計(jì)好,然后再調(diào)用drawRect方法畫(huà)上去。
layoutSubviews的調(diào)用時(shí)機(jī):
init時(shí)不會(huì)被調(diào)用
將要真正顯示的會(huì)調(diào)用
frame發(fā)現(xiàn)改變時(shí)智能調(diào)用
滾動(dòng)、旋轉(zhuǎn)、remove等等時(shí)
這些時(shí)機(jī)都是和frame相關(guān)的,也是唯一能更新子視圖的最好時(shí)機(jī)
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注