MyTextView.m 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // MyTextView.m
  3. // YBVideo
  4. //
  5. // Created by YunBao on 2018/6/25.
  6. // Copyright © 2018年 cat. All rights reserved.
  7. //
  8. #import "MyTextView.h"
  9. @implementation MyTextView
  10. - (void)awakeFromNib {
  11. [super awakeFromNib];
  12. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:)name:UITextViewTextDidChangeNotification object:nil];
  13. self.autoresizesSubviews = NO;
  14. self.placeholderColor = [UIColor whiteColor];
  15. }
  16. - (id)initWithFrame:(CGRect)frame {
  17. self = [super initWithFrame:frame];
  18. if (self) {
  19. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:)name:UITextViewTextDidChangeNotification object:nil];
  20. self.autoresizesSubviews = NO;
  21. self.placeholderColor = [UIColor whiteColor];
  22. }
  23. return self;
  24. }
  25. - (void)drawRect:(CGRect)rect {
  26. //内容为空时才绘制placeholder
  27. if ([self.text isEqual:@""]) {
  28. CGRect placeholderRect;
  29. placeholderRect.origin.y = 8;
  30. placeholderRect.origin.x = 8;
  31. placeholderRect.size.height = CGRectGetHeight(self.frame);
  32. placeholderRect.size.width = CGRectGetWidth(self.frame)-5;
  33. [self.placeholderColor set];
  34. NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
  35. paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
  36. NSDictionary *attribute=@{
  37. NSFontAttributeName:self.font,
  38. NSParagraphStyleAttributeName:paragraphStyle,
  39. NSForegroundColorAttributeName:self.placeholderColor,
  40. };
  41. [self.placeholder drawInRect:placeholderRect withAttributes:attribute];
  42. }
  43. }
  44. - (void)textChanged:(NSNotification *)not {
  45. [self setNeedsDisplay];
  46. }
  47. - (void)setText:(NSString *)text {
  48. [super setText:text];
  49. [self setNeedsDisplay];
  50. }
  51. @end