Advertisement
Guest User

Untitled

a guest
Feb 20th, 2015
356
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. import UIKit
  2.  
  3. class ThirdViewController: UIViewController {
  4. @IBOutlet weak var imageView: UIImageView!
  5.  
  6. @IBOutlet weak var myTextView: UITextView!
  7.  
  8. override func viewDidLoad() {
  9. super.viewDidLoad()
  10.  
  11. // Do any additional setup after loading the view.
  12. }
  13.  
  14. override func didReceiveMemoryWarning() {
  15. super.didReceiveMemoryWarning()
  16. // Dispose of any resources that can be recreated.
  17. }
  18.  
  19. func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
  20. // Combine the new text with the old
  21. let combinedText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)
  22.  
  23. // Create attributed version of the text
  24. let attributedText = NSMutableAttributedString(string: combinedText)
  25. attributedText.addAttribute(NSFontAttributeName, value: textView.font, range: NSMakeRange(0, attributedText.length))
  26.  
  27. // Get the padding of the text container
  28. let padding = textView.textContainer.lineFragmentPadding
  29.  
  30. // Create a bounding rect size by subtracting the padding
  31. // from both sides and allowing for unlimited length
  32. let boundingSize = CGSizeMake(textView.frame.size.width - padding * 2, CGFloat.max)
  33.  
  34. // Get the bounding rect of the attributed text in the
  35. // given frame
  36. let boundingRect = attributedText.boundingRectWithSize(boundingSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil)
  37.  
  38. // Compare the boundingRect plus the top and bottom padding
  39. // to the text view height; if the new bounding height would be
  40. // less than or equal to the text view height, append the text
  41. if (boundingRect.size.height + padding * 2 <= textView.frame.size.height){
  42. return true
  43. }
  44. else {
  45. return false
  46. }
  47. }
  48.  
  49.  
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement