Created
June 21, 2015 21:54
-
-
Save stuartjmoore/d3aca6fa50322ed723ef to your computer and use it in GitHub Desktop.
Fix Clipping UITextView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import XCPlayground | |
import UIKit | |
// MARK: - Paragraph Styles | |
let headlineParagraphStyle = NSMutableParagraphStyle() | |
headlineParagraphStyle.lineHeightMultiple = 0.8 | |
// MARK: Attributes | |
let attributes = [ | |
NSFontAttributeName: UIFont(name: "BanglaSangamMN-Bold", size: 42)!, | |
NSParagraphStyleAttributeName: headlineParagraphStyle | |
] | |
// MARK: String | |
let string = "Rivals pounce at 6 a.m. breakfast clubbin’" | |
let attributedString = NSAttributedString(string: string, attributes: attributes) | |
// MARK: - Views | |
let view = UIView(frame: UIScreen.mainScreen().bounds) | |
XCPShowView("view", view) | |
let textView = UITextView() | |
textView.frame = view.bounds | |
textView.editable = false | |
textView.selectable = false | |
textView.scrollEnabled = false | |
textView.textContainerInset = UIEdgeInsetsZero | |
textView.textContainer.lineFragmentPadding = 0 | |
textView.attributedText = attributedString | |
textView.textColor = UIColor.whiteColor() | |
textView.backgroundColor = UIColor(red: 0.99, green: 0.32, blue: 0.20, alpha:1) | |
view.addSubview(textView) | |
// MARK: - Measure Bounds | |
let maxSize = CGSize(width: view.bounds.width, height: CGFloat.max) | |
let options:NSStringDrawingOptions = .UsesLineFragmentOrigin | .UsesFontLeading | |
let boundingRect = attributedString.boundingRectWithSize(maxSize, options: options, context: nil) | |
textView.frame = CGRect(origin: CGPoint.zeroPoint, size: boundingRect.size) | |
// MARK: Shift Top Down | |
let font = attributes[NSFontAttributeName] as! UIFont | |
let paragraph = attributes[NSParagraphStyleAttributeName] as! NSParagraphStyle | |
let shiftTop = ceil(font.lineHeight - paragraph.lineHeightMultiple * font.lineHeight) | |
textView.textContainerInset.top = shiftTop | |
textView.frame.size.height += shiftTop |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment