Show More/ Show less in the end of UILabel in Swift - ios
I need to implement show more/ show less in UILabel like facebook. My label has mention and url features. Everything worked perfectly when there is no emoji in the text. I have added trailing at the end of the label by calculating textHeight and visible text of the label.
This is my extension file
//
// extension.swift
// SeeMore
//
// Created by Macbook Pro on 14/10/20.
//
import Foundation
import UIKit
//MARK : - text height, weidth
extension Range where Bound == String.Index {
var nsRange:NSRange {
return NSRange(location: self.lowerBound.encodedOffset,
length: self.upperBound.encodedOffset -
self.lowerBound.encodedOffset)
}
}
extension String {
var extractURLs: [URL] {
var urls : [URL] = []
var error: NSError?
let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
var text = self
detector!.enumerateMatches(in: text, options: [], range: NSMakeRange(0, text.count), using: { (result: NSTextCheckingResult!, flags: NSRegularExpression.MatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
// println("\(result)")
print("Extracted Result: \(result.url)")
urls.append(result.url!)
})
return urls
}
func textHeight(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedString.Key.font: font], context: nil)
return boundingBox.height
}
func textWidth(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
return boundingBox.width
}
}
extension UILabel{
func indexOfAttributedTextCharacterAtPoint(point: CGPoint, font : UIFont) -> Int {
guard let attributedString = self.attributedText else { return -1 }
let mutableAttribString = NSMutableAttributedString(attributedString: attributedString)
// Add font so the correct range is returned for multi-line labels
mutableAttribString.addAttributes([NSAttributedString.Key.font: font], range: NSRange(location: 0, length: attributedString.length))
let textStorage = NSTextStorage(attributedString: mutableAttribString)
let layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)
let textContainer = NSTextContainer(size: frame.size)
textContainer.lineFragmentPadding = 0
textContainer.maximumNumberOfLines = numberOfLines
textContainer.lineBreakMode = lineBreakMode
layoutManager.addTextContainer(textContainer)
let index = layoutManager.characterIndex(for: point, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
return index
}
func addTrailingForShowLess(with trailingText: String, moreText: String, moreTextFont: UIFont, moreTextColor: UIColor, complition: #escaping (_ attribute: NSMutableAttributedString) -> Void) {
let readMoreText: String = trailingText + moreText
if let myText = self.text {
let trimmedString: String? = myText + trailingText
let readMoreLength: Int = (readMoreText.count)
guard let safeTrimmedString = trimmedString else { return }
if safeTrimmedString.count <= readMoreLength { return }
print("less this number \(safeTrimmedString.count) should never be less\n")
print("less then this number \(readMoreLength)")
// "safeTrimmedString.count - readMoreLength" should never be less then the readMoreLength because it'll be a negative value and will crash
// let trimmedForReadMore: String = (safeTrimmedString as NSString).replacingCharacters(in: NSRange(location: safeTrimmedString.count, length: readMoreLength), with: "") + trailingText
let answerAttributed = NSMutableAttributedString(string: safeTrimmedString, attributes: [NSAttributedString.Key.font: moreTextFont])
let readMoreAttributed = NSMutableAttributedString(string: moreText, attributes: [NSAttributedString.Key.font: moreTextFont, NSAttributedString.Key.foregroundColor: moreTextColor])
answerAttributed.append(readMoreAttributed)
complition(answerAttributed)
// self.attributedText = answerAttributed
}
}
func addTrailing(with trailingText: String, moreText: String, moreTextFont: UIFont, moreTextColor: UIColor, complition: #escaping (_ attribute: NSMutableAttributedString) -> Void) {
let readMoreText: String = trailingText + moreText
if self.text?.count == 0 { return }
if self.visibleTextLength == 0 { return }
let lengthForVisibleString: Int = self.visibleTextLength
if let myText = self.text {
let mutableString: String = myText
let trimmedString: String? = (mutableString as NSString).replacingCharacters(in: NSRange(location: lengthForVisibleString, length: myText.count - lengthForVisibleString), with: "")
let readMoreLength: Int = (readMoreText.count + 2)
guard let safeTrimmedString = trimmedString else { return }
if safeTrimmedString.count <= readMoreLength { return }
print("this number \(safeTrimmedString.count) should never be less\n")
print("then this number \(readMoreLength)")
// "safeTrimmedString.count - readMoreLength" should never be less then the readMoreLength because it'll be a negative value and will crash
let trimmedForReadMore: String = (safeTrimmedString as NSString).replacingCharacters(in: NSRange(location: safeTrimmedString.count - readMoreLength, length: readMoreLength), with: "") + trailingText
let answerAttributed = NSMutableAttributedString(string: trimmedForReadMore, attributes: [NSAttributedString.Key.font: moreTextFont])
let readMoreAttributed = NSMutableAttributedString(string: moreText, attributes: [NSAttributedString.Key.font: moreTextFont, NSAttributedString.Key.foregroundColor: moreTextColor])
answerAttributed.append(readMoreAttributed)
complition(answerAttributed)
// self.attributedText = answerAttributed
}
}
var visibleTextLength: Int {
let font: UIFont = self.font
let mode: NSLineBreakMode = self.lineBreakMode
let screenSize = UIScreen.main.bounds
let labelWidth: CGFloat = self.frame.size.width
let labelHeight: CGFloat = self.frame.size.height
let sizeConstraint = CGSize(width: labelWidth, height: CGFloat.greatestFiniteMagnitude)
if let myText = self.text {
let attributes: [AnyHashable: Any] = [NSAttributedString.Key.font: font]
let attributedText = NSAttributedString(string: myText, attributes: attributes as? [NSAttributedString.Key : Any])
let boundingRect: CGRect = attributedText.boundingRect(with: sizeConstraint, options: .usesLineFragmentOrigin, context: nil)
if boundingRect.size.height > labelHeight {
var index: Int = 0
var prev: Int = 0
let characterSet = CharacterSet.whitespacesAndNewlines
repeat {
prev = index
if mode == NSLineBreakMode.byCharWrapping {
index += 1
} else {
index = (myText as NSString).rangeOfCharacter(from: characterSet, options: [], range: NSRange(location: index + 1, length: myText.count - index - 1)).location
}
} while index != NSNotFound && index < myText.count && (myText as NSString).substring(to: index).boundingRect(with: sizeConstraint, options: .usesLineFragmentOrigin, attributes: attributes as? [NSAttributedString.Key : Any], context: nil).size.height <= labelHeight
return prev
}
}
if self.text == nil {
return 0
} else {
return self.text!.count
}
}
}
This is my tableView cell
//
// PostTableViewCell.swift
// SeeMore
//
// Created by Macbook Pro on 14/10/20.
//
import UIKit
protocol PostTableViewCellDelegate {
func postLabelAction(cell: PostTableViewCell, post: Post, tap: UITapGestureRecognizer)
}
class PostTableViewCell: UITableViewCell {
#IBOutlet weak var postLabel: UILabel!
var currentPost : Post?
var delegate: PostTableViewCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
postLabel.textColor = .black
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(postLabelSelected))
tapGesture.numberOfTapsRequired = 1
postLabel.isUserInteractionEnabled = true
postLabel.addGestureRecognizer(tapGesture)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
#objc func postLabelSelected(tap: UITapGestureRecognizer) {
delegate?.postLabelAction(cell: self, post: currentPost!, tap: tap)
}
func applyAttributedStringToPost(attributedString: NSMutableAttributedString, item: Post) {
let text = attributedString.string
let urls = text.extractURLs
for url in urls {
let range1 = (text as NSString).range(of: url.absoluteString)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: range1)
postLabel.attributedText = attributedString
}
postLabel.attributedText = attributedString
}
func setupItems(item : Post){
currentPost = item
let postText = item.postText
postLabel.numberOfLines = item.isExpendable ? 0 : 4
postLabel.text = postText
let underlineAttriString = NSMutableAttributedString(string: postText)
let urls = postText.extractURLs
for url in urls {
let range1 = (postText as NSString).range(of: url.absoluteString)
underlineAttriString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: range1)
postLabel.attributedText = underlineAttriString
}
//Apply See more see less
postLabel.sizeToFit()
// let screenSize = UIScreen.main.bounds/
if let newfont = postLabel.font {
let textHeight = postText.textHeight(withConstrainedWidth: postLabel.frame.size.height, font: newfont)
if item.isExpendable {
postLabel.addTrailingForShowLess(with: "...", moreText: "Show Less", moreTextFont: newfont, moreTextColor: UIColor.blue) { (attributedString) in
self.applyAttributedStringToPost(attributedString: attributedString, item: item)
}
} else if postLabel.frame.size.height < textHeight, !item.isExpendable {
postLabel.addTrailing(with: "...", moreText: "Show More", moreTextFont: newfont, moreTextColor: UIColor.blue) { (attributedString) in
self.applyAttributedStringToPost(attributedString: attributedString, item: item)
}
}
}
}
}
This is my view controller
// ViewController.swift
// SeeMore
//
// Created by Macbook Pro on 14/10/20.
//
import UIKit
struct Post {
var postText = ""
var isExpendable = false
}
class ViewController: UIViewController {
var postArray : [Post] = [Post]()
#IBOutlet weak var postTableView: UITableView!{
didSet{
settingUpTableView()
}
}
override func viewDidLoad() {
super.viewDidLoad()
fillUpPostData()
postTableView.reloadData()
}
func settingUpTableView() {
let nib = UINib(nibName: "PostTableViewCell", bundle: nil)
postTableView.register(nib, forCellReuseIdentifier: "PostTableViewCell")
postTableView.rowHeight = UITableView.automaticDimension
postTableView.estimatedRowHeight = 300
postTableView.separatorStyle = .singleLine
postTableView.separatorInset = .zero
}
func fillUpPostData() {
postArray.append(Post(postText: "Next, we established questions. We usedโliberally to indicate questions, and ๐ค to indicate โIโm not understanding.โ Iโd say questions composed about 30โ40% of our communication, so this was a critical emoji discovery.\nThen, we added more interesting complex relationships. ๐ implied that, after time, one thing would lead to another. ๐ค๐๐ฃ๏ธ means that โIโll be able to talk soon.โ We created a scale for asking โHow do you feel?โ: ๐๐๐๐โน๏ธ๐ดโ\nAs our communication advanced, we adopted each othersโ language. My friend used ๐บ to indicate โand.โ After I understood, I started adopting the same emoji meaning. Since communication was so challenging and time-intensive, cooperating on each othersโ emoji meaning was critical.\nTime in emoji is very expressive. ๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐ ๐ก๐ข๐ฃ๐ค๐ฅ๐ฆ๐ง allowed us to communicate time very easily", isExpendable: false))
postArray.append(Post(postText: "Apple has just finished its โHi, Speedโ event, where it finally took the wraps off the four new iPhone 12 phones, which have all-new designs and will all support 5G wireless networks. Apple also unveiled the HomePod mini, a smaller and more affordable version of the HomePod smart speaker.\nIf you want to read the play-by-play of the event, check out our live blog with commentary from Dieter Bohn and Nilay Patel. But if you just want to read the biggest news from the show, weโve got you covered right here.\nApple has just finished its โHi, Speedโ event, where it finally took the wraps off the four new iPhone 12 phones, which have all-new designs and will all support 5G wireless networks. Apple also unveiled the HomePod mini, a smaller and more affordable version of the HomePod smart speaker.\nIf you want to read the play-by-play of the event, check out our live blog with commentary from Dieter Bohn and Nilay Patel. But if you just want to read the biggest news from the show, weโve got you covered right here....Show Less", isExpendable: false))
postArray.append(Post(postText: "Next, we established questions. We usedโliberally to indicate questions, and ๐ค to indicate \"Iโm not understanding.\" Iโd say questions composed about 30โ40% of our communication, so this was a critical emoji discovery.\nThen, we added more interesting complex relationships. ๐ implied that, after time, one thing would lead to another. ๐ค๐๐ฃ๏ธ means that \"Iโll be able to talk soon.\" We created a scale for asking โHow do you feel?\": ๐๐๐๐โน๏ธ๐ดโ\nAs our communication advanced, we adopted each othersโ language. My friend used ๐บ to indicate \"and.", isExpendable: false))
postArray.append(Post(postText: "BIG breaking news! Trump is going to have a fit over this one. โA former Department of Homeland Security official questioned in a scathing op-ed how anyone could vote for President Donald Trump in the 2020 election, citing the chaos that has characterized his administration and his mishandling of the coronavirus pandemic.\nElizabeth Neumann explained in a USA Today column ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐๐๐๐๐๐๐บ๐ธ๐บ๐ธ๐๐๐๐๐๐โค๏ธ๐๐ปโฆ๏ธ๐ค๐๐๐๐๐ published Tuesday why she is โconvincedโ the president is โfailing at keeping Americans safe.โ Neumann, until April, spent three years as a high-ranking member of the Trump administrationโs national security team.\nโHe is dangerous for our country,โ she wrote.\nNeumann cited the presidentโs failure to address the surge in white nationalist violence, his constant lying and the turnover of key administration officials. Without elaborating, she also referred to what she said was a close call that could have led the U.S. into war.\n\nShe warned the countryโs abandonment of allies and appeasement of dictators would โonly get worseโ in a second Trump term. Her column is headlined:ย โTrump made it hard for me to protect America. How could I vote for him again? How could anyone?โ\n\nNeumann, ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐๐๐๐๐๐๐บ๐ธ๐บ๐ธ๐๐๐๐๐๐โค๏ธ๐๐ปโฆ๏ธ๐ค๐๐๐๐๐ who endorsed Democratic nominee Joe Biden in a video released by the Republican Voters Against Trump group in August, had particularly harsh commentary on the pandemic.\n\nTrumpโs intentional public dismissal of the threat of COVID-19 โ while acknowledging its โdeadlyโ nature in private โ was worse than a โdereliction of duty,โ said Neumann.\n\nโYour government is supposed to perform some basic functions; keeping you and your family safe is primary among them,โ she wrote. โIn 2016, I voted for President Trump. But when someone asked me if I could vote for him again, after he time and again refused to keep Americans safe โย how could I say anything but no? How could anyone?โ ", isExpendable: false))
postArray.append(Post(postText: " \n\n\nHere is her entire op-Ed: Everything we saw during the first presidential debate is indicative of how President Donald Trump behaves in the White House. His business model is chaos. ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐๐๐๐๐๐๐บ๐ธ๐บ๐ธ๐๐๐๐๐๐โค๏ธ๐๐ปโฆ๏ธ๐ค๐๐๐๐๐He has no organization, no leadership, and sees every interaction as a contest or a battle, even when it doesnโt have to be. Chris Wallace now knows how so many administration staffers feel โ and how I felt when the president got in the way of me doing my job. He is dangerous for our country.\n\nI served as the Assistant Secretary of Homeland Security for Counterterrorism and Threat Prevention, and my job was to help keep Americans safe from terrorist attacks. My time in office coincided with a dramatic rise in white nationalist violence, but my colleagues and I couldnโt get the president to help address the problem. At the debate, America saw what I saw in the administration: President Trump refuses to distance himself from white nationalists. ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐๐๐๐๐๐๐บ๐ธ๐บ๐ธ๐๐๐๐๐๐โค๏ธ๐๐ปโฆ๏ธ๐ค๐๐๐๐๐I realized after watching the White House response to the terrorist attack in El Paso that his rhetoric was a recruitment tool for violent extremist groups. The president bears some responsibility for the deaths of Americans at the hands of these violent extremists.\n\n\nAs a conservative, I believe a primary purpose of the federal government is to provide for the national defense. Under the Constitution, it is a mandatory function of the federal government. After serving for three years inside the Trump administrationโs national security team, I am convinced the president is failing at keeping Americans safe.\n\nEarly on in the administration, I represented the Department of Homeland Security at several meetings in which a White House staff member implied that the president had approved, and that we should begin to carry out, plans that could have led the United States into war. Thankfully, there were experienced people in the room who had enough clout to suggest that these catastrophic plans needed a second look. Many of us werenโt sure what, if anything, the president had actually approved, or that he had been properly briefed to ensure he understood the risks involved. These people helped us avoid war.", isExpendable: false))
postArray.append(Post(postText: "\n\nHaving adults in the room matters. They protect the country from a chaotic White House structure that allows staffers to run amok. But more importantly, they ensure that the president is presented with unvarnished truth, that difficult topics like domestic terrorism are raised even when he ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐๐๐๐๐๐๐บ๐ธ๐บ๐ธ๐๐๐๐๐๐โค๏ธ๐๐ปโฆ๏ธ๐ค๐๐๐๐๐doesnโt want to acknowledge them.\n\nEvery day, the number of experienced people in the administration that have the ability to speak truth to power shrinks. We are seeing the results: abandoning our allies and cozying up to dictators, emboldening our enemies and weakening our standing in the world. This would only get worse in a second Trump term.\n\nJust as he ignored white nationalists, he also ignored COVID-19. After nearly 20 years around national crises, you can recognize a good response โ and a bad one. By late January, professionals and outside experts were sounding the alarms. Health and Human Services Secretary Alex Azar declared a public health emergency on Jan. 31. But throughout February, longtime colleagues at the Federal ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐๐๐๐๐๐๐บ๐ธ๐บ๐ธ๐๐๐๐๐๐โค๏ธ๐๐ปโฆ๏ธ๐ค๐๐๐๐๐Emergency Management Agency were privately expressing dismay at the flailing response.\n\nBob Woodwardโs revelations last month, using the presidentโs own words, demonstrate that the governmentโs failure wasnโt just because of bureaucracy, the newness of the virus, or even the president sticking his head in the sand. It was intentional. This is worse than dereliction of duty โ this is willfully leading defenseless people to a killer. President Trump repeatedly lied to the American public. Those lies have led to more deaths and illnesses.\n\nA recent study assessed that had we exercised our pandemic mitigation plans (which have existed since 2005), as other wealthy countries did, nearly 9 million more Americans would be employed, and over 100,000 would still be alive. We could have saved half of the Americans who have died so far.\n\nYour government is supposed to perform some basic functions; keeping you and your family safe is primary among them. In 2016, I voted for President Trump. But when someone asked me if I could vote for him again, after he time and again refused to keep Americans safe โ how could I say anything but no? How could anyone?...Show Less", isExpendable: false))
postArray.append(Post(postText: "\nPamela Lindsay:\nโjust another conspiracy theory that proved to be untrue look at all the money he has wasted for something that was patently untrue. how many does this make that he yelled about some half baked ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐๐๐๐๐๐๐บ๐ธ๐บ๐ธ๐๐๐๐๐๐โค๏ธ๐๐ปโฆ๏ธ๐ค๐๐๐๐๐conspiracy theory that just showed how desperate he is. yet look at the number that will still follow him he and they are truly deplorable.\nBeverly Jones: โTax dollars wasted in another attempt to blame a former President of wrong-doing. Since we already know #45's wrongdoings, an investigation will cost nothing.", isExpendable: false))
postArray.append(Post(postText: "Judy Stamberger:\n \"AN incredible, 8 yrs served with dignity, kindness, no lawsuits, arrests, no impeachment, no crude remarks, respectful man & his family.\"\nJames S Lechleitnerjr:\n\"Outstanding men Martin Luther King, and President Barack Obama...\nAmenโ๏ธ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐บ๐ธ๐๐๐๐๐๐๐บ๐ธ๐บ๐ธ๐๐๐๐๐๐โค๏ธ๐๐ปโฆ๏ธ๐ค๐๐๐๐๐โผ๏ธ\"\nCarol Brown-Hatcher:\n\"Greatness, Grace, Integrity, Honorable(Men,) Brilliant, Humble, Brave, Courageous. THEY WOULD NOT BE SILENCED. They knew the meaning of \"Responsibility\".", isExpendable: false))
postArray.append(Post(postText: "BRAVO! ๐ We love this!!! A North Dakota farmer is going viral for plowing a pro-Biden-Harris message into his field. Peter Larson says that this is the first time he has used his fields to share his political views. He hopes to encourage others to get out and vote. Great idea, Peter! ๐๐๐ Follow Ridin' With Biden to defeat Trump and save America! ๐บ๐ธ๐บ๐ธ๐บ๐ธ...Show Less", isExpendable: false))
postArray.append(Post(postText: "Ridin' With Biden:\n\"Olivia Troye, who until a couple of months ago was on Mike Pence's FAILED Coronavirus \"Response\" Task Force, just slammed Trump for PRETENDING that Dr. Fauci praised Trump's disastrous COVID response in a misleading campaign ad. Follow Ridin' With Biden to defeat Trump and save America!\" ๐บ๐ธ๐บ๐ธ๐บ๐ธ", isExpendable: false))
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PostTableViewCell", for: indexPath) as! PostTableViewCell
cell.setupItems(item: postArray[indexPath.row])
cell.delegate = self
return cell
}
}
extension ViewController: PostTableViewCellDelegate{
func postLabelAction(cell: PostTableViewCell,post: Post, tap: UITapGestureRecognizer) {
let tapLocation = tap.location(in: cell.postLabel)
let tapIndex = cell.postLabel.indexOfAttributedTextCharacterAtPoint(point: tapLocation, font: cell.postLabel.font!)
var rangeArray: [NSRange] = [NSRange]()
var linkRangeArray: [NSRange] = [NSRange]()
let postText = cell.postLabel.text
var seemoreText = ""
seemoreText = post.isExpendable ? "Show Less" : "Show More"
//
if let seeRange = postText?.range(of: seemoreText)?.nsRange {
if tapIndex > seeRange.location && tapIndex < seeRange.location + seeRange.length {
if let indexPath = postTableView.indexPath(for: cell) {
let isExpanded = self.postArray[indexPath.row].isExpendable
self.postArray[indexPath.row].isExpendable = !isExpanded
DispatchQueue.main.async { [weak self] in
self?.postTableView.reloadRows(at: [indexPath], with: .automatic)
self?.postTableView.scrollToRow(at: indexPath, at: .top, animated: true)
}
return
}
}
}
if let urls = postText?.extractURLs {
for url in urls {
guard let range = postText?.range(of: url.absoluteString)?.nsRange else { return }
linkRangeArray.append(range)
}
for (index, neRange) in linkRangeArray.enumerated() {
if tapIndex > neRange.location && tapIndex < neRange.location + neRange.length {
print("link print")
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LinkPreviewWebViewController") as! LinkPreviewWebViewController
vc.loadURL = urls[index].absoluteString
self.navigationController?.isNavigationBarHidden = false
self.navigationController?.pushViewController(vc, animated: true)
return
}
}
}
// mention logic will be there
}
}
If there are emoji's or extra line gap before post text visibleTextLength return wrong count as a result users can't see the show more text because it is below visible text. even label.frame.size doesn't give me the current width of the different devices. Any help will be greatly appreciated. TIA
[Please ignore the post text as it's taken from real user to produce the problem]
It should be mentioned that i have tried Expendable Label and ReadMoreTextView but they can't serve me well.
This the output with the problem i'm facing
You can use https://github.com/apploft/ExpandableLabel this Class for show more/read more/more functionality in UILabel. This class is Customizable as per your requirements. I use this it will working fine.
I hope it will work for you.
Thanks.
Related
How to improve NSTextStorage addAttribute performance
I have a long text (probably usual book like >200 pages) in NSTextStorage. I'm distributing this text for textContainers this way: let textStorageLength = defaultTextStorage?.length ?? 0 while layoutManager!.textContainer(forGlyphAt: textStorageLength - 1, effectiveRange: nil) == nil { let textContainer = NSTextContainer(size: textContainerSize) layoutManager!.addTextContainer(textContainer) pagesCount += 1 } Then I use this containers for textViews on pageViewController. I have some words marking like: func selectTappableWordsFromList(_ list: [PositionWithWord]) { self.defaultTextStorage?.beginEditing() list.forEach { if !self.shouldInterruptCurrentProcesses { self.markWordInDefaultTextStorage(positionWithWord: $0) } else { self.shouldInterruptCurrentProcesses = false self.defaultTextStorage?.endEditing() return } } self.defaultTextStorage?.endEditing() } func markWordInDefaultTextStorage(positionWithWord: PositionWithWord) { let range = NSMakeRange(positionWithWord.position!.start, positionWithWord.position!.length) defaultTextStorage?.addAttributes(defaultAttributes, range: range) } let defaultAttributes: [NSAttributedStringKey: Any] = [ .underlineStyle: NSUnderlineStyle.styleSingle.rawValue, .underlineColor: UIColor.BookReader.underline ] The problem is: marking words in whole text storage is working very slow. The more pages in the book, the slower it works. Also screenshot of cpu usage from profiler. Any way to improve logic?
Swift 3, Display some lines of the HTML text
I try to add html code inside webView: webView.loadHTMLString(myHTML, baseURL: nil) But last line displays cropped: What is the best way to hide this cropped bottom line in my webView?
I recommend you too use UILabel Full example ViewController.swift import UIKit class ViewController: UIViewController { var label: UILabel? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.lightGray var bounds = view.bounds bounds.origin.y = 44 bounds.size.height = 100 label = UILabel(frame: bounds) label?.backgroundColor = UIColor.white view.addSubview(label!) let filename = "HTMLPage.html" if let path = Bundle.main.path(forResource: filename, ofType: nil) { do { let text = try String(contentsOfFile: path, encoding: String.Encoding.utf8) label?.attributedText = text.htmlToAttributedString label?.numberOfLines = 5 label?.lineBreakMode = .byTruncatingTail } catch { print("Failed to read text from \(filename)") } } else { print("Failed to load file from app bundle \(filename)") } } } extension String { var htmlToAttributedString: NSAttributedString? { do { let data = self.data(using: String.Encoding.utf8, allowLossyConversion: true) if let d = data { let str = try NSAttributedString(data: d, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) return str } } catch { } return nil } } HTMLPage.html <div style="font-family:'Helvetica'; font-size: 11pt;"><div class="feed-description"><p>The apple tree (Malus pumila, commonly and erroneously called Malus domestica) is a deciduous tree in the rose family best known for its sweet, pomaceous fruit, the apple. link It is cultivated worldwide as a fruit tree, and is the most widely grown species in the genus Malus. The tree originated in Central Asia, where its wild ancestor, Malus sieversii, is still found today. Apples have been grown for thousands of years in Asia and Europe, and were brought to North America by European colonists. Apples have religious and mythological significance in many cultures, including Norse, Greek and European Christian traditions. link text text text</p></div></div> Result
Swift - Textview Identify Tapped Word Not Working
Long time user, first time poster, so my apologies if I make any errors in presenting my question. I have been working on this for hours and I've decided it is time to ask the experts. I have also searched through every similar question that has been "answered" and work, which leads me to believe they are outdated. I am attempting to grab the tapped word from a UITextview that would be used later in the code. For example, there is a paragraph of words in the text view: "The initial return on time investment is much smaller, due to him trading his upfront cost for sweat-equity in the company, but the potential long-term payout is much greater". I would want to be able to tap on a word, e.g. 'investment', and run it through another function to define it. However simply tapping the word, crashes the program, and I do not receive the word tapped. I implemented a tap gesture recognizer: let tap = UITapGestureRecognizer(target: self, action: #selector(tapResponse(_:))) tap.delegate = self tvEditor.addGestureRecognizer(tap) and then wrote the function: 2 func tapResponse(recognizer: UITapGestureRecognizer) { let location: CGPoint = recognizer.locationInView(tvEditor) let position: CGPoint = CGPointMake(location.x, location.y) let tapPosition: UITextPosition = tvEditor.closestPositionToPoint(position)! let textRange: UITextRange = tvEditor.tokenizer.rangeEnclosingPosition(tapPosition, withGranularity: UITextGranularity.Word, inDirection: 1)! let tappedWord: String = tvEditor.textInRange(textRange)! print("tapped word : %#", tappedWord) } Ideally, this should take the location from the tapped part of the Textview, take the position by taking the .x & .y, and then looking through the Textview at the point closest to the position, finding the Range enclosing the position with granularity (to return the word), and setting the contents as a String, which I am currently just printing to the console. However, on tapping the word, I receive this crash.3 along with "fatal error: unexpectedly found nil while unwrapping an Optional value" in the console. Any help would be greatly appreciated. I may just be missing something simple, or it could be much more complicated.
Whenever the tapped received at the blank spaces between the words, tapPosition returned by the TextView can be nil nil. Swift has new operator called optional ? which tells the compiler that the variable may have nil value. If you do not use ? after the variable name indicates that the variable can never have nil value. In Swift, using ! operator means you are forcing the compiler to forcefully extract the value from the optional variable. So, in that case, if the value of the variable is nil, it will crash on forcing. So, what is actually happening is You are creating the variable let tapPosition: UITextPosition, let textRange: UITextRange and let tappedWord: String are not optional return type of the method myTextView.closestPositionToPoint(position), tvEditor.textInRange(textRange) are optional variable UITextPosition?, String? Assigning a value of optional variable to non optional variable requires ! The method is returning nil and you are forcing it to get the value ! lead to CRASH What you can do Before forcing any optional variable, just be sure that it has some value using if variable != nil { print(variable!) } Correct method would be as func tapResponse(recognizer: UITapGestureRecognizer) { let location: CGPoint = recognizer.locationInView(myTextView) let position: CGPoint = CGPointMake(location.x, location.y) let tapPosition: UITextPosition? = myTextView.closestPositionToPoint(position) if tapPosition != nil { let textRange: UITextRange? = myTextView.tokenizer.rangeEnclosingPosition(tapPosition!, withGranularity: UITextGranularity.Word, inDirection: 1) if textRange != nil { let tappedWord: String? = myTextView.textInRange(textRange!) print("tapped word : ", tappedWord) } } }
Swift 3.0 Answer - Working as of July 1st, 2016 In my ViewDidLoad() - I use text from a previous VC, so my variable "theText" is already declared. I included a sample string that has been noted out. //Create a variable of the text you wish to attribute. let textToAttribute = theText // or "This is sample text" // Break your string in to an array, to loop through it. let textToAttributeArray = textToAttribute.componentsSeparatedByString(" ") // Define a variable as an NSMutableAttributedString() so you can append to it in your loop. let attributedText = NSMutableAttributedString() // Create a For - In loop that goes through each word your wish to attribute. for word in textToAttributeArray{ // Create a pending attribution variable. Add a space for linking back together so that it doesn't looklikethis. let attributePending = NSMutableAttributedString(string: word + " ") // Set an attribute on part of the string, with a length of the word. let myRange = NSRange(location: 0, length: word.characters.count) // Create a custom attribute to get the value of the word tapped let myCustomAttribute = [ "Tapped Word:": word] // Add the attribute to your pending attribute variable attributePending.addAttributes(myCustomAttribute, range: myRange) print(word) print(attributePending) //append 'attributePending' to your attributedText variable. attributedText.appendAttributedString(attributePending) /////// print(attributedText) } textView.attributedText = attributedText // Add your attributed text to textview. Now we will add a tap gesture recognizer to register taps. let tap = UITapGestureRecognizer(target: self, action: #selector(HandleTap(_:))) tap.delegate = self textView.addGestureRecognizer(tap) // add gesture recognizer to text view. Now we declare a function under the viewDidLoad() func HandleTap(sender: UITapGestureRecognizer) { let myTextView = sender.view as! UITextView //sender is TextView let layoutManager = myTextView.layoutManager //Set layout manager // location of tap in myTextView coordinates var location = sender.locationInView(myTextView) location.x -= myTextView.textContainerInset.left; location.y -= myTextView.textContainerInset.top; // character index at tap location let characterIndex = layoutManager.characterIndexForPoint(location, inTextContainer: myTextView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil) // if index is valid then do something. if characterIndex < myTextView.textStorage.length { // print the character index print("Your character is at index: \(characterIndex)") //optional character index. // print the character at the index let myRange = NSRange(location: characterIndex, length: 1) let substring = (myTextView.attributedText.string as NSString).substringWithRange(myRange) print("character at index: \(substring)") // check if the tap location has a certain attribute let attributeName = "Tapped Word:" //make sure this matches the name in viewDidLoad() let attributeValue = myTextView.attributedText.attribute(attributeName, atIndex: characterIndex, effectiveRange: nil) as? String if let value = attributeValue { print("You tapped on \(attributeName) and the value is: \(value)") } } }
In addition to #AmitSingh answer, this is updated Swift 3.0 version: func didTapTextView(recognizer: UITapGestureRecognizer) { let location: CGPoint = recognizer.location(in: textView) let position: CGPoint = CGPoint(x: location.x, y: location.y) let tapPosition: UITextPosition? = textView.closestPosition(to: position) if tapPosition != nil { let textRange: UITextRange? = textView.tokenizer.rangeEnclosingPosition(tapPosition!, with: UITextGranularity.word, inDirection: 1) if textRange != nil { let tappedWord: String? = textView.text(in: textRange!) print("tapped word : ", tappedWord!) } } } The other code is the same as his. Hope it helps!
Make Clickable UILabel Using Swift
I want to Set Particular Word clickable in UILabel text using Swift. Is it possible? If more than one label is here how can I detect which word is pressed?
You can not do with the simple label. There is library available in the github. https://github.com/TTTAttributedLabel/TTTAttributedLabel From this you can use the method called yourLabel.addLinkToURL() class ViewController: UIViewController , TTTAttributedLabelDelegate{ #IBOutlet var lbl: TTTAttributedLabel! override func viewDidLoad() { super.viewDidLoad() var str : NSString = "Hello this is link" lbl.delegate = self lbl.text = str as String var range : NSRange = str.rangeOfString("link") lbl.addLinkToURL(NSURL(string: "http://github.com/mattt/")!, withRange: range) } func attributedLabel(label: TTTAttributedLabel!, didSelectLinkWithURL url: NSURL!) { UIApplication.sharedApplication().openURL(url) } }
SWIFT 3.0 privacyLabel.delegate = self let strPolicy : NSString = "Agree to the Terms & Conditions" privacyLabel.text = strPolicy as String let range1 : NSRange = strPolicy.range(of: "Terms & Conditions") privacyLabel.addLink(to: URL(string: "http://Terms.com")!, with: range1) func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith url: URL!) { print("url \(url)") // UIApplication.sharedApplication().openURL(url) }
I'd like to share my library https://github.com/psharanda/Atributika It contains modern replacement of TTTAtributedLabel + powerful set of methods to detect and style different stuff like tags, hashtags, mentions etc (everything of that can be clickable) Some code to show how it works: let link = Style .font(.boldSystemFont(ofSize: 14)) .foregroundColor(.black) .foregroundColor(.red, .highlighted) let tos = link.named("tos") let pp = link.named("pp") let all = Style .font(.systemFont(ofSize: 14)) .foregroundColor(.gray) let text = "<tos>Terms of Service</tos> and <pp>Privacy Policy</pp>" .style(tags: tos, pp) .styleAll(all) let tosLabel = AttributedLabel() tosLabel.textAlignment = .center tosLabel.attributedText = text tosLabel.onClick = { label, detection in switch detection.type { case .tag(let tag): switch tag.name { case "pp": print("Privacy Policy clicked") case "tos": print("Terms of Service clicked") default: break } default: break } } view.addSubview(tosLabel)
Ruby text/ Furigana in ios
I am currently trying to display some text in Japanese on a UITextView. Is it possible to display the furigana above the kanji (like below) in a manner similar to the < rt> tag in html, without using a web view? A lot of text processing is involved, therefore I cannot simply use a web view. In iOS8, CTRubyAnnotationRef was added but there is no documentation (I would welcome any example), and I am also concerned with the lack of compatibility with iOS7. I thought that it would be possible to display the furigana above with the use of an NSAttributedString, but couldn't as of yet.
Update Swift 5.1 This solution is an update of preview answers and let you write Asian sentences with Phonetic Guide, using a pattern in the strings. Let's start from handling string. these 4 extension let you to inject in a string the ruby annotation. the function createRuby() check the string a pattern, that it is: ๏ฝword written in kanjiใphonetic guideใ. Examples: ๏ฝ็ด ็ใใซใใผใ ๏ฝๆๅใใใใใใใใใใฉใใใฏใใใฟใฎ๏ฝๅชๅใใฉใใใใใซ๏ฝไฟใใใใใใ and so on. the important thing is to follow the pattern. extension String { // ๆๅญๅใฎ็ฏๅฒ private var stringRange: NSRange { return NSMakeRange(0, self.utf16.count) } // ็นๅฎใฎๆญฃ่ฆ่กจ็พใๆค็ดข private func searchRegex(of pattern: String) -> NSTextCheckingResult? { do { let patternToSearch = try NSRegularExpression(pattern: pattern) return patternToSearch.firstMatch(in: self, range: stringRange) } catch { return nil } } // ็นๅฎใฎๆญฃ่ฆ่กจ็พใ็ฝฎๆ private func replaceRegex(of pattern: String, with templete: String) -> String { do { let patternToReplace = try NSRegularExpression(pattern: pattern) return patternToReplace.stringByReplacingMatches(in: self, range: stringRange, withTemplate: templete) } catch { return self } } // ใซใใ็ๆ func createRuby() -> NSMutableAttributedString { let textWithRuby = self // ใซใไปๆๅญ(ใ๏ฝ็ด ็ใใซใใผใใ)ใ็นๅฎใๆๅญๅใๅๅฒ .replaceRegex(of: "(๏ฝ.+?ใ.+?ใ)", with: ",$1,") .components(separatedBy: ",") // ใซใไปๆๅญใฎใซใใ่จญๅฎ .map { component -> NSAttributedString in // ใใผในๆๅญ(ๆผขๅญใชใฉ)ใจใซใใใใใใๅๅพ guard let pair = component.searchRegex(of: "๏ฝ(.+?)ใ(.+?)ใ") else { return NSAttributedString(string: component) } let component = component as NSString let baseText = component.substring(with: pair.range(at: 1)) let rubyText = component.substring(with: pair.range(at: 2)) // ใซใใฎ่กจ็คบใซ้ขใใ่จญๅฎ let rubyAttribute: [CFString: Any] = [ kCTRubyAnnotationSizeFactorAttributeName: 0.5, kCTForegroundColorAttributeName: UIColor.darkGray ] let rubyAnnotation = CTRubyAnnotationCreateWithAttributes( .auto, .auto, .before, rubyText as CFString, rubyAttribute as CFDictionary ) return NSAttributedString(string: baseText, attributes: [kCTRubyAnnotationAttributeName as NSAttributedString.Key: rubyAnnotation]) } // ๅๅฒใใใฆใใๆๅญๅใ็ตๅ .reduce(NSMutableAttributedString()) { $0.append($1); return $0 } return textWithRuby } } Ruby Label: the big problem As you maybe know, Apple has introduced in iOS 8 the ruby annotation like attribute for the attributedString, and if you did create the the attributed string with ruby annotation and did: myLabel.attributedText = attributedTextWithRuby the label did shows perfectly the string without problem. From iOS 11, Apple unfortunately has removed this feature and, so, if want to show ruby annotation you have override the method draw, to effectively draw the text. To do this, you have to use Core Text to handle the text hand it's lines. Let's show the code import UIKit public enum TextOrientation { //1 case horizontal case vertical } class RubyLabel: UILabel { public var orientation:TextOrientation = .horizontal //2 // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. // ใซใใ่กจ็คบ override func draw(_ rect: CGRect) { //super.draw(rect) //3 // context allows you to manipulate the drawing context (i'm setup to draw or bail out) guard let context: CGContext = UIGraphicsGetCurrentContext() else { return } guard let string = self.text else { return } let attributed = NSMutableAttributedString(attributedString: string.createRuby()) //4 let path = CGMutablePath() switch orientation { //5 case .horizontal: context.textMatrix = CGAffineTransform.identity; context.translateBy(x: 0, y: self.bounds.size.height); context.scaleBy(x: 1.0, y: -1.0); path.addRect(self.bounds) attributed.addAttribute(NSAttributedString.Key.verticalGlyphForm, value: false, range: NSMakeRange(0, attributed.length)) case .vertical: context.rotate(by: .pi / 2) context.scaleBy(x: 1.0, y: -1.0) //context.saveGState() //self.transform = CGAffineTransform(rotationAngle: .pi/2) path.addRect(CGRect(x: self.bounds.origin.y, y: self.bounds.origin.x, width: self.bounds.height, height: self.bounds.width)) attributed.addAttribute(NSAttributedString.Key.verticalGlyphForm, value: true, range: NSMakeRange(0, attributed.length)) } attributed.addAttributes([NSAttributedString.Key.font : self.font], range: NSMakeRange(0, attributed.length)) let frameSetter = CTFramesetterCreateWithAttributedString(attributed) let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0,attributed.length), path, nil) // Check need for truncate tail //6 if (CTFrameGetVisibleStringRange(frame).length as Int) < attributed.length { // Required truncate let linesNS: NSArray = CTFrameGetLines(frame) let linesAO: [AnyObject] = linesNS as [AnyObject] var lines: [CTLine] = linesAO as! [CTLine] let boundingBoxOfPath = path.boundingBoxOfPath let lastCTLine = lines.removeLast() //7 let truncateString:CFAttributedString = CFAttributedStringCreate(nil, "\u{2026}" as CFString, CTFrameGetFrameAttributes(frame)) let truncateToken:CTLine = CTLineCreateWithAttributedString(truncateString) let lineWidth = CTLineGetTypographicBounds(lastCTLine, nil, nil, nil) let tokenWidth = CTLineGetTypographicBounds(truncateToken, nil, nil, nil) let widthTruncationBegins = lineWidth - tokenWidth if let truncatedLine = CTLineCreateTruncatedLine(lastCTLine, widthTruncationBegins, .end, truncateToken) { lines.append(truncatedLine) } var lineOrigins = Array<CGPoint>(repeating: CGPoint.zero, count: lines.count) CTFrameGetLineOrigins(frame, CFRange(location: 0, length: lines.count), &lineOrigins) for (index, line) in lines.enumerated() { context.textPosition = CGPoint(x: lineOrigins[index].x + boundingBoxOfPath.origin.x, y:lineOrigins[index].y + boundingBoxOfPath.origin.y) CTLineDraw(line, context) } } else { // Not required truncate CTFrameDraw(frame, context) } } //8 override var intrinsicContentSize: CGSize { let baseSize = super.intrinsicContentSize return CGSize(width: baseSize.width, height: baseSize.height * 1.0) } } Code explanation: 1- Chinese and japanese text can be written in horizontal and vertical way. This enumeration let you switch in easy way between horizontal and vertical orietantation. 2- public variable with switch orientation text. 3- this method must be commented. the reason is that call it you see two overlapping strings:one without attributes, last your attributed string. 4- here call the method of String class extension in which you create the attributed string with ruby annotation. 5- This switch, rotate if need the context in which draw your text in case you want show vertical text. In fact in this switch you add the attribute NSAttributedString.Key.verticalGlyphForm that in case vertical is true, false otherwise. 6- This 'if' is particular important because, the label, cause we had commented the method 'super.draw()' doesn't know how to manage a long string. without this 'if', the label thinks to have only one line to draw. And so, you still to have a string with '...' like tail. In this 'if' the string is broken in more line and drawing correctly. 7- When you don't give to label some settings, the label knows to have more one line but because it can't calculate what is the showable last piece of string, give error in execution time and the app goes in crash. So be careful. But, don't worry! we talk about the right settings to give it later. 8- this is very important to fit the label to text's size. How to use the RubyLabel the use of the label is very simple: import UIKit class ViewController: UIViewController { #IBOutlet weak var rubyLabel: RubyLabel! //1 override func viewDidLoad() { super.viewDidLoad() setUpLabel() } private func setUpLabel() { rubyLabel.text = "๏ฝๆๅใใใใใใใใใใฉใใใฏใใใฟใฎ๏ฝๅชๅใใฉใใใใใซ๏ฝไฟใใใใใใ๏ฝไบบใ ใใฒใจใณใจใใฎ๏ฝ็ๆญปใใใใใใซ๏ฝไฟใใใใใใ" //2 //3 rubyLabel.textAlignment = .left rubyLabel.font = .systemFont(ofSize: 20.0) rubyLabel.orientation = .horizontal rubyLabel.lineBreakMode = .byCharWrapping } } Code Explanation: 1- connect label to xib if use storyboard or xib file or create label. 2- as I say, the use is very simple: here assign the string with ruby pattern like any other string 3- these setting are the setting to have to set to make work the label. You can set via code or via storyboard/xib Be careful if you use storyboard/xib, if you don't put correctly the constraints, the label give you the error at point nยฐ 7. Result Works, but not perfect As you can see by screenshot, this label work well but still has some problem. 1- with vertical text the label still in horizontal shape; 2- if the string contains \n to split the string in more lines, the label shows only the number of lines that the string would have had if was without the '\n' character. I'm working for fix these problem, but your help is appreciated.
In the end I created a function that gets the kanji's position and create labels every time, above the kanji. It's quite dirty but it's the only way to insure a compatibility with iOS7. However I have to mention the remarkable examples that you can find on GitHub for the CTRubyAnnotationRef nowadays like : http://dev.classmethod.jp/references/ios8-ctrubyannotationref/ and https://github.com/shinjukunian/SimpleFurigana Good luck to all of you !
Here's a focused answer with some comments. This works for UITextView and UILabel on iOS 16. let rubyAttributes: [CFString : Any] = [ kCTRubyAnnotationSizeFactorAttributeName : 0.5, kCTRubyAnnotationScaleToFitAttributeName : 0.5, ] let annotation = CTRubyAnnotationCreateWithAttributes( .center, // Alignment relative to base text .auto, // Overhang for adjacent characters .before, // `before` = above, `after` = below, `inline` = after the base text (for horizontal text) "Ruby!" as CFString, rubyAttributes as CFDictionary ) let stringAttributes = [kCTRubyAnnotationAttributeName as NSAttributedString.Key : annotation] NSAttributedString(string: "Base Text!", attributes: stringAttributes) Note, you may want to UITextView.textContainerInset.top to something larger than the default to avoid having the ruby clipped by the scrollview.