IM模块--UItextView带有placeholder属性,自动调节高度

╰半夏微凉° 2022-09-25 01:23 43阅读 0赞
  1. 参考资料:

[简书地址](http://www.jianshu.com/users/23d0ae412e19/latest_articles)

  1. #import <UIKit/UIKit.h>
  2. @interface MessageInputView : UITextView
  3. @property (nonatomic,copy) void (^UpdateTextFrame)(CGFloat th) ;
  4. @end
  5. #import "MessageInputView.h"
  6. @interface MessageInputView()<UITextViewDelegate>
  7. @property (nonatomic,strong) UILabel *placeholderLabel;
  8. @end
  9. @implementation MessageInputView
  10. - (instancetype)initWithFrame:(CGRect)frame{
  11. self = [super initWithFrame:frame];
  12. if (self) {
  13. [self setUpUi];
  14. }
  15. return self;
  16. }
  17. - (void)setUpUi{
  18. _placeholderLabel = [[UILabel alloc]init];
  19. _placeholderLabel.font = [UIFont systemFontOfSize:15];
  20. _placeholderLabel.text = @"请输入";
  21. _placeholderLabel.textColor = [UIColor lightGrayColor];
  22. [self addSubview:_placeholderLabel];
  23. self.layer.cornerRadius = 6;
  24. self.layer.masksToBounds = YES;
  25. self.delegate = self;
  26. self.showsHorizontalScrollIndicator = NO;
  27. self.showsVerticalScrollIndicator = NO;
  28. self.scrollEnabled = NO;
  29. // 文本有改动的时候通知 ---
  30. [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textViewChange) name:UITextViewTextDidChangeNotification object:nil];
  31. }
  32. - (void)layoutSubviews{
  33. [super layoutSubviews];
  34. _placeholderLabel.frame = CGRectMake(5, 0, self.bounds.size.width, self.bounds.size.height);
  35. }
  36. - (void)textViewChange{
  37. if (self.text.length == 0) {
  38. _placeholderLabel.hidden = NO;
  39. }else{
  40. _placeholderLabel.hidden = YES;
  41. }
  42. }
  43. #pragma mark UITextViewDelegate
  44. - (void)textViewDidChange:(UITextView *)textView{
  45. // 获取当前 TextView的高度
  46. CGFloat tH = [textView sizeThatFits:textView.frame.size].height;
  47. NSLog(@"%f",tH);
  48. // 修改高度
  49. if (self.UpdateTextFrame != nil) {
  50. self.UpdateTextFrame(tH);
  51. }
  52. }
  53. @end
  54. - (void)viewDidLoad {
  55. [super viewDidLoad];
  56. self.view.backgroundColor = [UIColor grayColor];
  57. MessageInputView *messageView = [[MessageInputView alloc]initWithFrame:CGRectMake(50, 400, 100, 30)];
  58. __block MessageInputView *blockSelf = messageView;
  59. [messageView setUpdateTextFrame:^(CGFloat th) {
  60. [UIView animateWithDuration:0.2 animations:^{
  61. blockSelf.frame = CGRectMake(50, 400, 100, th);
  62. }];
  63. }];
  64. [self.view addSubview:messageView];
  65. }

发表评论

表情:
评论列表 (有 0 条评论,43人围观)

还没有评论,来说两句吧...

相关阅读

    相关 uni-app input高度调节

    在某些情况下 自己定义的高度无法实现展示,不管是设置了height还是line-height,父元素也设置了最后结果还是不起作用,在这样的情况下 你就应该考虑下设置下min-h

    相关 Android亮度自动调节

    最近在做人脸识别项目。在抓取人脸时,发现了很多问题。其中旋转角度和光线问题最令人抓狂。 Camera拍摄照片可能存在0度/90度/180度/270度的(右侧)旋转,不同设备不