ResizingLabel.m 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2014-2020 Threema GmbH
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU Affero General Public License, version 3,
  11. // as published by the Free Software Foundation.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. #import "ResizingLabel.h"
  21. @interface ResizingLabel ()
  22. @end
  23. @implementation ResizingLabel
  24. - (id) initWithFrame:(CGRect)frame
  25. {
  26. self = [super initWithFrame:frame];
  27. if (self) {
  28. _maxHeight = 0.0;
  29. }
  30. return self;
  31. }
  32. - (void)setText:(NSString *)text
  33. {
  34. self.numberOfLines = _maxLines;
  35. [super setText: text];
  36. }
  37. - (CGSize) sizeThatFits:(CGSize)size
  38. {
  39. return CGSizeMake(size.width, [self calculateHeightThatFits]);
  40. }
  41. - (CGFloat) calculateHeightThatFits
  42. {
  43. CGSize size = [self.text sizeWithAttributes:@{NSFontAttributeName : self.font}];
  44. if (size.width < self.frame.size.width && [self containsNewLine: self.text] == NO) {
  45. self.numberOfLines = 1;
  46. return fmaxf(size.height + _paddingHeight, _minHeight);
  47. } else {
  48. self.numberOfLines = _maxLines;
  49. CGSize maxSize = CGSizeMake(self.frame.size.width, _maxHeight - _paddingHeight);
  50. CGSize uiLabelSize = [super sizeThatFits: maxSize];
  51. if (_maxHeight > 0.0) {
  52. int maxPossibleLines = (_maxHeight - _paddingHeight) / size.height;
  53. CGFloat height = MIN(maxPossibleLines * size.height, uiLabelSize.height);
  54. return height + _paddingHeight;
  55. } else {
  56. return uiLabelSize.height + _paddingHeight;
  57. }
  58. }
  59. }
  60. - (BOOL) containsNewLine: (NSString *) string
  61. {
  62. NSRange range = [string rangeOfString:@"\n"];
  63. if (range.location != NSNotFound) {
  64. return YES;
  65. }
  66. return NO;
  67. }
  68. @end