How to bold TextView with custom Font in Swift? - swift

I want to change my text in textview to BOLD and Italic on button click; but when I do this the custom font which is I am using for my textview also changed; but I want to use custom font.
Following is the code for bold textview
textView.font = UIFont.boldSystemFont(ofSize: 20)
I want to use custom font even when using bold or italic style
I have tried this but it does not work.
func attributedText() -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: textView.text, attributes: [NSAttributedString.Key.font:(name: CustomFont, size: CGFloat(fontSize))]
let boldFontAttribute = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 15.0)]
// 4
return attributedString
}
And called as:
textView.attributedText = attributedText()

You can't make a regular font look bold, instead you need to have a bold font face for your custom font family (separate file) and add it together with regular font to your project's .plist as shown here.
For example if your font is called a CustomFont, then you'd add the following files into your project
CustomFont
CustomFont-Bold
Now you get a bold font as
let boldFont = UIFont(name: "CustomFont-Bold", size: ...)

Related

Is it possible to Change the Regular font to Bold of UILable text?

I have a Label with custom font Unica One-Regular. Since, it is not available in bold font, I am getting problem to make it bold. Is there any way to make it bold?. Here is the font link.
https://fonts.google.com/specimen/Unica+One?selection.family=Unica+One
Thanks in advance.
Sorry I’m on my iPhone but,
Please check the exact name of the font on Xcode, but this code should answer your question :
let attrs:[String:AnyObject] = [NSFontAttributeName: UIFont(name: "Unica One-Bold", size: 12)!]
let boldString = NSMutableAttributedString(string: "text", attributes:attrs)
let lbl = UILabel()
lbl.attributedText = boldString
There is a more recent answer to this question at Is it possible to increase the boldness of the font if the bold font file is not available?.
Short summary: if you have a list of font attributes, you can add a negative stroke width. For example (in Swift):
import AppKit
guard let chosenFont = NSFont(name: "VTypewriter Underwood", size: 24) else {
print("No such font")
exit(1)
}
var fontAttributes = [
NSAttributedString.Key.font:chosenFont,
NSAttributedString.Key.strokeWidth:NSNumber(value:-3.0)
]
let fakelyBoldedText = NSAttributedString(string:"Hello World", attributes:fontAttributes)
This is not optimal; it isn’t really bolding. But with low values for the stroke width (in my experiments, from about -3 to -5, possibly relative to the font width), it does look bolded.

Changing the font size of an NSButton doesn't change anything

I'm working on my first Swift project (hooray), which is an app for Mac OS. What I want to do now is create some buttons, with a white text color and a custom font. Because I needed a new attribute on that button to hold some data, I made a child class of NSButton.
Now, I know that I can set the font of a button like this:
super.font = NSFont(name: "NB-International-Pro", size: 40)
Which worked like a charm. After that I tried to change the color of the text by doing this:
let pstyle = NSMutableParagraphStyle()
pstyle.alignment = .center
super.attributedTitle = NSAttributedString(string: (device?.name)!, attributes: [ NSForegroundColorAttributeName : NSColor.white, NSParagraphStyleAttributeName : pstyle ])
Which did work, and it did change the color of the text, however, now the font and font size are back to default. Is there an option to do both?
Thanks.
Instead of setting the font first, include the font name and size in your attributes when creating your NSAttributedString by using the NSFontAttributeName and NSFontSizeAttribute keys:
attributedTitle = NSAttributedString(string: (device?.name)!, attributes: [ NSForegroundColorAttributeName : NSColor.white, NSParagraphStyleAttributeName : pstyle, NSFontAttributeName: "NB-International-Pro", NSFontSizeAttribute: 40])
Beyond that there's probably some improvements you can make to the architecture of your code. Subclassing NSButton is not really needed just for changing text style (can be done either in .xib or your view controller).

How to change CenterText Font in PieChart in ios-charts?

I would like to change the Center Text Font and Font Size of a PieChart. I would like to make it as big as it's possible inside the center circle. Is there any on-board feature that helps me to change the font and font size or do i have to overwrite some Framework classes?
Didn't find any useful information in the documentation :(
That's my basic Chart Formating method:
func setAttributes(view: PieChartView){
view.legend.enabled = true
view.descriptionText = ""
view.userInteractionEnabled = false
view.drawSliceTextEnabled = false
view.animate(xAxisDuration: 2.0, yAxisDuration: 2.0, easingOption: ChartEasingOption.EaseInOutBack)
}
Regards!
Swift 3
You can use this code to change font in swift 3.
let myAttribute = [ NSFontAttributeName: UIFont(name: "IranSansMobile", size: 15.0)! ]
let myAttrString = NSAttributedString(string: "My String", attributes: myAttribute)
chart.centerAttributedText = myAttrString
The centered text in pie chart is called centerAttributedText, in PieChartView. It's NSAttributedText, so you can define many custom attributes.
You can simply change its font and size like below:
centerText = #"Whatever you like";
[centerText setAttributes:#{
NSFontAttributeName: [UIFont fontWithName:#"HelveticaNeue-Light" size:12.f],
NSParagraphStyleAttributeName: paragraphStyle
} range:NSMakeRange(0, centerText.length)];
pieChartView.centerAttributedText = centerText;
It's in Objective-C, but should be easy for you to translate into swift, since you only need to care about the attributes
swift 5
var pieChartView = PieChartView()
...
let myAttrString = NSAttributedString(string: "My String", attributes: nil)
pieChartView.centerAttributedText = myAttrString

how to make text bold for detailedTextLabel in swift

cell!.textLabel?.text = vehicle["vrn"].string
cell?.detailTextLabel?.text = stateString
I want to display stateString as bold and also tried to use textLabel instead of detailedText but it did not work.
You can set the font property of the detailTextLabellike so:
cell.detailTextLabel?.font = UIFont.boldSystemFontOfSize(15.0)
You can use the font property inside the UILabel class.
// You need to set the name of your font here
cell.detailTextLabel?.font = UIFont(name:"HelveticaNeue-Bold", size: 16.0)
There are other options using the attributedText
property but implies a little more of code, something like this:
// Define attributes to set
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 16)
let attributes :Dictionary = [NSFontAttributeName : labelFont]
// Create the attributed string
var attrString = NSAttributedString(string: "textOfYourLabel", attributes:attributes)
cell.detailTextLabel?.attributedText = attrString
I hope this help you.
If you want to bold text label using story board, simply select SHADOW colour in attributes inspector to same of that Text colour. Its works for me try it....

Underline text in a UITextView

How can I underline text in a UITextView. I understand that I would need to create a subclass of UITextView, but what would go under drawRect:?
Thanks.
Try to use NSAttributedString as follows and set in UITextView. This works for iOS6.
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:#"Some String"];
[attString addAttribute:(NSString*)kCTUnderlineStyleAttributeName
value:[NSNumber numberWithInt:kCTUnderlineStyleSingle]
range:(NSRange){0,[attString length]}];
For more info on NSAttributedString check this How do you use NSAttributedString?
For eg:-
textView.attributedText = attString;
From apple documentation on UITextView,
In iOS 6 and later, this class supports multiple text styles through
use of the attributedText property. (Styled text is not supported in
earlier versions of iOS.) Setting a value for this property causes the
text view to use the style information provided in the attributed
string. You can still use the font, textColor, and textAlignment
properties to set style attributes, but those properties apply to all
of the text in the text view.
attributedText:
The styled text displayed by the text view.
#property(nonatomic,copy) NSAttributedString *attributedText
Discussion: This property is nil by default. Assigning a new value to this property also replaces the value of the text property with the same string data, albeit without any formatting information. In addition, assigning a new a value updates the values in the font, textColor, and textAlignment properties so that they reflect the style information starting at location 0 in the attributed string.
If you want to avoid having to include CoreText, you can utilize an attributed string with this attribute:
#{NSUnderlineStyleAttributeName: #(NSUnderlineStyleSingle)}
If this is static text, you can underline it in Interface Builder. Make sure to make the text 'Attributed' first by selecting 'Attributed' in the drop down menu:
textViewMessage.linkTextAttributes = #{NSForegroundColorAttributeName: [UIColor blueColor], NSUnderlineStyleAttributeName: [NSNumber numberWithInt:NSUnderlineStyleSingle]};
If you want to format your text (with underlined words, links, colored words...) I suggest you to use FTCoreText
-(IBAction)underline:(id)sender
{
NSDictionary *underlineAttribute = #{NSUnderlineStyleAttributeName: #(NSUnderlineStyleSingle)};
texts.attributedText = [[NSAttributedString alloc] initWithString:texts.text
attributes:underlineAttribute];
}
You can't use "kCTUnderlineStyleAttributeName" or "kCTUnderlineStyleSingle"
Now you must do it like this:
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:#"Text"];
[attString addAttribute:NSUnderlineStyleAttributeName
value:#(NSUnderlineStyleSingle)
range:(NSRange){0,[attString length]}];
If you are using iOS 6 then you can use the attributedText attribute of UITextView. Apply underline formatting to the text. You can also set the typingAttributes property to ensure the text that the user types has a specific set of formatting if you wish.
I recommend you to use CoreText. A Basic tutorial is here on raywenderlich.
I recommend you to use MFUnderlinedTextView, it will be helpful.
This is how I did it using Swift 5:
let attributedString = NSMutableAttributedString(string: myTextView.text ?? "")
myTextView.linkTextAttributes = [NSAttributedString.Key(rawValue: NSAttributedString.Key.underlineStyle.rawValue): NSUnderlineStyle.single.rawValue] as [NSAttributedString.Key: Any]?
myTextView.attributedText = attributedString
Swift 5.
As my UITextView if for inserting text, I created an extension function as bellow.
extension UITextView {
func underlined() {
let border = CALayer()
let width = CGFloat(1.0)
border.borderColor = UIColor.lightGray.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - 5, width: self.frame.size.width, height: 1)
border.borderWidth = width
self.layer.addSublayer(border)
self.layer.masksToBounds = true
let style = NSMutableParagraphStyle()
style.lineSpacing = 15
let attributes = [NSAttributedString.Key.paragraphStyle : style, NSAttributedString.Key.foregroundColor : UIColor.darkGray, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 13)]
self.attributedText = NSAttributedString(string: self.text, attributes: attributes)
}
}
The border is drawling the line and the style is adding the spacing between the lines.
Usage in your UIView custom layout:
override func layoutSubviews() {
super.layoutSubviews()
self.dateAndTimeInput.underlined()
}
Image with the result
let someString = NSMutableAttributedString(string: "Your String", attributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.underlineStyle : NSUnderlineStyle.single.rawValue])
someStringTextView.attributedText = titleAT
U can just give your string a bunch of attributes like bold, underlined etc.
To underline a text, you have to go where you can select copy, cut , delete options there are now more options like B/I/U( bold, italic, underline). Choose this option and this is it. And to unable it, choose underline option again.