String with multilpe attributes in swift - ios

I am working on an app on which i had to make the text in a UITextView bold or italic or underlined. So i came up with this solution to make the selected range from the textView bold. The same way i can make it italic and but not underlined, don't know how.
//MARK: Bold Bar Button
func boldBarButtonClicked(sender : UIBarButtonItem)
{
if let selectedTextRange = self.textView.selectedTextRange
{
let beginningOfDocument = self.textView.beginningOfDocument
let startingPoint = self.textView.offsetFromPosition(beginningOfDocument, toPosition: selectedTextRange.start)
let selectedTextLength = self.textView.offsetFromPosition(selectedTextRange.start, toPosition: selectedTextRange.end)
let dict : Dictionary<String, AnyObject> = self.textView.textStorage.attributesAtIndex(startingPoint, effectiveRange: nil)
if let currentFont = dict[NSFontAttributeName] as? UIFont
{
let fontDescriptor = currentFont.fontDescriptor()
let changedFontDescriptor = fontDescriptor.fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits.TraitBold)
let updatedFont = UIFont(descriptor: changedFontDescriptor, size: 0.0)
let updatedDict = [NSFontAttributeName : updatedFont ]
self.textView.textStorage.beginEditing()
let selectedNSRange = NSMakeRange(startingPoint, selectedTextLength)
self.textView.textStorage.setAttributes(updatedDict, range: selectedNSRange)
self.textView.textStorage.endEditing()
// Put bold tag inside letters
}
}
}
So basically when the user sees the textView i have to make the text bold. So i thought of putting the text in between bold tag just the same as html. So that i can loop through the characters and see whether there is any text which is bold or italic or underline.
Am i doing it the correct way? Finding the selected range make it bold or italic or underlined and then put the tag inside the reference string, finally passing this string to the server with tags involved, so that others can see where comes the bold or italic or underlined characters.
How this will work if the same string has multiple attributes like, if the string "alvin" has bold and italic and underline, it will be like U I B "alvin' /U /I /B (tags are same as html bold, italic, underline) correct? How can i do find these in Swift, i thought about it a lot and tired of using regular expressions and looping through the string. But could not get the proper result. Thanks in advance.

Related

Check font is only bold not extrabold, semibold or any ohter bold

i'm using font.fontDescriptor.symbolicTraits.contains(.traitBold) but this function is returns true if font is semibold, extra bold or any other bold type.
i need solution for i have bold font then get true and i have semibold, extra bold or any other bold then get false.
You can use something like:
let attributes = font.fontDescriptor.fontAttributes
let traits = attributes[.traits] as? [UIFontDescriptor.TraitKey : Any]
let weight = traits[.weight] as? UIFont.Weight
Then, you can compare the weight to .bold.

Programatically change some words' color in an UITextView

So I have an UITextView with some text and I want everytime the user inputs, for example, the word "while", after it has been written it should change into purple. Also, I have another UITextView just to display content, no user interaction enabled, and I want that everytime the view appears, all the "while" words to also be purple. How do I do this? Can you help me, please? Thank you!
Here's what I've tried so far:
let initialText = textView.text!
let string_to_color = "while"
let range = (initialText as NSString).range(of: string_to_color)
let attribute = NSMutableAttributedString.init(string: initialText)
attribute.addAttribute(NSForegroundColorAttributeName, value: UIColor.purple, range: range)
textView.attributedText = attribute
But it colors only the first word. This is for the user interaction disabled text field. I haven't figured out how to do it for the text field that contains the words that the user inputs.
You are not getting the range correctly, here is an example of using attributed strings in Swift 3.0:
// get initial text as a String type (you will get this from your textview)
let initialText = "Swift Attributed String"
// create an attribute for the text color, I chose blue color
let myAttribute = [ NSForegroundColorAttributeName: UIColor.blue ]
// create the attributed string and add the blue color attribute
let myString = NSMutableAttributedString(string: initialText, attributes: myAttribute )
// range starting at location 6 with a lenth of 10: "Attributed"
var myRange = NSRange(location: 6, length: 10)
// OR get range of specific string in initialText
let newRange = (initialText as NSString).range(of: "Attributed")
// change the range of the word "Attributed" to have red text color
myString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: newRange)
// create another attribute for highlighting
let anotherAttribute = [ NSBackgroundColorAttributeName: UIColor.yellow ]
// set the range of the "Attributed" part of the string to a yellow highlight
myString.addAttributes(anotherAttribute, range: newRange)
You can use this strategy to do whatever formatting you need to do with your string. Just make sure that the range that you are getting is correct.

Manage alignment in custom font in iOS

I am using custom font in my code. After using it, letters are not aligned in one line which is causing UI issues.
I want to change font or label setting so that it look like below :
Any help?
I think, it is due to the Font style so you can set the text as NSAttributedString String and manage the Font accordingly. In that case create two NSMutableAttributedString with different Attributesand use it.
extension String {
func getText() -> NSAttributedString {
let str1 = "Hello"
let str2 = "750"
//create attribute
let attStr1 = NSMutableAttributedString(string: str1)
let attFormat = [NSFontAttributeName : UIFont.systemFontOfSize(10.0)]
let attString = NSMutableAttributedString(string: str2, attributes: attFormat)
attString.appendAttributedString(attStr1)
return attString
}
}
Just create Attribute according to your requirement and it will work.

Adding underline attribute to partial text UILabel in storyboard

How can I underline partial text of UILabel using only storyboard? I am able to do this in code and I'm able to underline the entire text of a label, but not just one or two words in the string.
select the UILabel and go to Attribute Inspector section.
Change the text value from plain to Attributed .
Select the particular part of text which you want to Underline .
Note: If u want full text to be Underline select full text.
Now right click and change the font to Underline.
It will Underline the text
Steps:-
Go to TextEdit and create your UILabel text with underline.
Change UILabel text to Attributed (Attributed Selector).
Copy Underlined text and assign to UILabel.
Through code:
func underLineText(text: String)-> NSMutableAttributedString
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(NSMutableAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: attributedText.length))
return attributedText
}
//calling of func
yourLbl.attributedText = underLineText(text:yourLbl.text!)
List of other underline Types
NSMutableAttributedString.Key.underlineStyle = NSUnderlineStyle.single.rawValue
NSMutableAttributedString.Key.underlineStyle = NSUnderlineStyle.thick.rawValue
NSMutableAttributedString.Key.underlineStyle = NSUnderlineStyle.double.rawValue
NSMutableAttributedString.Key.underlineStyle = NSUnderlineStyle.patternDot.rawValue
NSMutableAttributedString.Key.underlineStyle = NSUnderlineStyle.patternDash.rawValue
NSMutableAttributedString.Key.underlineStyle = NSUnderlineStyle.patternDashDot.rawValue
NSMutableAttributedString.Key.underlineStyle = NSUnderlineStyle.patternDashDotDot.rawValue
NSMutableAttributedString.Key.underlineStyle = NSUnderlineStyle.byWord.rawValue

Using MMMarkdown, only system font will show bold or italicized text

I'm using MMMarkdown and when I apply no font to UILabel or UITextView (I have to keep UITextView so TTTAttributedLabel won't do), all of markdown works. When I give the label or textview a font, I only get markdown hyperlinks to work. I tried switching to the AttributedMarkdown library but hyperlinks don't work at all with that one.
In my Markdown Class:
class Markdown: NSObject {
func markdownString(stringForVideoDescription:NSString) -> NSMutableAttributedString {
var options = [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType]
var error:NSError?
var markdown:NSString = stringForVideoDescription
var html:NSString = MMMarkdown.HTMLStringWithMarkdown(markdown, error: &error)
var markdownAttributedString:NSMutableAttributedString = NSMutableAttributedString(data: html.dataUsingEncoding(NSUTF32StringEncoding)!, options: options, documentAttributes: nil, error: &error)!
if let font: UIFont = UIFont(name: "Marion-Regular", size: 14) {
markdownAttributedString.addAttributes([NSUnderlineStyleAttributeName:NSUnderlineStyleAttributeName], range: NSMakeRange(0, markdownAttributedString.length))
}
println(html) // used to see that markdown is in fact working
return markdownAttributedString
}
In my view, I'm actually pulling from json api but I replace to test with:
let bodyText = "\*This* sample \[I'm an inline-style link](https://www.google.com)"
myTextView.attributedText = Markdown().markdownString(bodyText)
Do I need to set up css to specify font for each bold, italicized text? Any help is greatly appreciated as my designers don't want to use the default font of Times New Roman.

Resources