Skip to content

Instantly share code, notes, and snippets.

@stuartjmoore
Created June 21, 2015 21:54
Show Gist options
  • Save stuartjmoore/d3aca6fa50322ed723ef to your computer and use it in GitHub Desktop.
Save stuartjmoore/d3aca6fa50322ed723ef to your computer and use it in GitHub Desktop.
Fix Clipping UITextView
//: 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