Putting a superscript in a label in xcode8 - swift

I am creating a math app and would like to have a superscript 2. I have been unable to find a solution for xcode 8 that isn't a base line off set
finalFunc.text = "Converted: \(printA)(x+\(printB))^2+\(printC)"

Updated for Swift4
let font:UIFont? = UIFont(name: "Helvetica", size:20)
let fontSuper:UIFont? = UIFont(name: "Helvetica", size:10)
let attString:NSMutableAttributedString = NSMutableAttributedString(string: "xcode8", attributes: [NSAttributedString.Key.font:font!])
attString.setAttributes([NSAttributedString.Key.font:fontSuper!,NSAttributedString.Key.baselineOffset:10], range: NSRange(location:5,length:1))
labelname.attributedText = attString

Use this code -
let font:UIFont? = UIFont(name: "Helvetica", size:20)
let fontSuper:UIFont? = UIFont(name: "Helvetica", size:10)
let attString:NSMutableAttributedString = NSMutableAttributedString(string: "xcode8", attributes: [NSFontAttributeName:font!])
attString.setAttributes([NSFontAttributeName:fontSuper!,NSBaselineOffsetAttributeName:10], range: NSRange(location:5,length:1))
label1.attributedText = attString;
Output -

For a simple to use Swift solution, you might want to checkout HandyUIKit. After importing it into your project (e.g. via Carthage – see instructions in README) you can do something like this:
import HandyUIKit
let someFont = UIFont.systemFont(ofSize: 20, weight: .medium)
"Converted: \(printA)(x+\(printB))^{2}+\(printC)".superscripted(font: someFont)
The last line will return an NSAttributedString which will look exactly like what you're looking for. Just assign it to a UILabels attributedText property and that's it!
If you're looking for subscripting a text, simply use subscripted(font:) instead. It will recognize structures like CO_{2}. There's also superAndSubscripted(font:) if you want to combine both.
See the docs for more information and additional examples.

Related

Why is using UIControlState.normal on a segmented control causing this crash?

I have a simple UISegmentedControl with two segments and I'm trying to customize its appearance.
I'm getting this runtime error:
*** Terminating app due to uncaught exception >'NSInvalidArgumentException', reason: '-[NSNull renderingMode]: unrecognized selector sent to instance 0x112156f08'
#IBOutlet weak var sortController: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
styleSortController()
// other setup code
}
func styleSortController() {
let titleAttributes: [String: Any] = [NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont(name: "AvenirNext-Demi", size: CGFloat(14.0)) as Any]
let selectedTitleAttributes: [String: Any] = [NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: UIFont(name: "AvenirNext-DemiBold", size: CGFloat(14.0)) as Any]
// this line causes it to crash
sortController.setTitleTextAttributes(titleAttributes, for: UIControlState.normal)
// but this line works, no problem
sortController.setTitleTextAttributes(selectedTitleAttributes, for: UIControlState.selected)
}
caused by the line seen above where I first try to set a title text attribute (note that the second line setting an attribute works just fine).
According to Apple's documentation, I should be able to use any valid UIControlState and UIControlState.normal sure seems valid so I'm really confused about why this is happening.
What could this line be causing me trouble?
let titleAttributes: [String: Any] = [NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: UIFont(name: "AvenirNext-Demi", size: CGFloat(14.0)) as Any]
let selectedTitleAttributes: [String: Any] = [NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: UIFont(name: "AvenirNext-DemiBold", size: CGFloat(14.0)) as Any]
Before saying it's the UIControlState issue, you need to do:
sortController.setTitleTextAttributes(selectedTitleAttributes, for: UIControlState.normal)
In other words, use the same working sample (the one for .selected)
It should create the same error crash.
Then you'll find that the culprit is UIFont(name: "AvenirNext-Demi", size: CGFloat(14.0)), it returns nil.
So the font name is not a valid one.
You can iterate through your Font to list it (see this related question) and find the correct one.
It's a "usual one", so you can open Font Book.app, find it, and check the Post script name of it. Not all font in macOS are in iOS, but that's the case for that one.
You'll get: AvenirNext-Regular, AvenirNext-Medium, AvenirNext-UltraLight, AvenirNext-Italic, AvenirNext-MediumItalic, AvenirNext-UltraLightItalic, AvenirNext-DemiBold, AvenirNext-Bold, AvenirNext-Heavy, AvenirNext-DemiBoldItalic, AvenirNext-BoldItalic, AvenirNext-HeavyItalic.
There is no AvenirNext-Demi.
So use the one you think fit more your need.
I recommend if you use custom font to install them in your Mac. It's easy to checkout the postscript name of the font that way.
First problem I see is that lot of code you wrote had been renamed in Swift 4. Attributes format [String: Any] is no longer supported. You have to use [NSAttributedString.Key: Any].
For example: NSForegroundColorAttributeName --> NSAttributedString.Key.foregroundColor
Second, font AvenirNext hasn't any style "Demi", it has just "DemiBold".
let titleAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont(name: "AvenirNext-DemiBold", size: CGFloat(14.0)) as Any]
let selectedTitleAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont(name: "AvenirNext-DemiBold", size: CGFloat(14.0)) as Any]

Multiline multicolor attributed text in swift

How can I build something like this using attributed text? I tried adding line feed (\n), it didn't work, just displayed first line and cropped next two, removing \n will display two parts in single line:
let mutableAttributedString = NSMutableAttributedString()
let regularAttribute = [NSAttributedStringKey.font: UIFont(name: "Avenir-Light", size: 45.0), NSAttributedStringKey.foregroundColor: UIColor.yellow]
let boldAttribute = [NSAttributedStringKey.font: UIFont(name: "Avenir-Light", size: 25.0), NSAttributedStringKey.foregroundColor: UIColor.white]
let mutableAttributedString2 = NSMutableAttributedString()
let boldAttributedString = NSAttributedString(string: "person", attributes: boldAttribute)
let regularAttributedString = NSAttributedString(string: "\(self.requestCount)", attributes: regularAttribute)
mutableAttributedString2.append(boldAttributedString)
mutableAttributedString2.append(NSAttributedString(string: "\n"))
mutableAttributedString2.append(regularAttributedString)
self.btnStatsPeople.setAttributedTitle(mutableAttributedString2, for: .normal)
UILabel has one line by default.
This property controls the maximum number of lines to use in order to
fit the label’s text into its bounding rectangle. The default value
for this property is 1. To remove any maximum limit, and use as many
lines as needed, set the value of this property to 0.
UIButton creates default UILabel. So using 0 lines is a solution for your problem:
self.btnStatsPeople.titleLabel?.numberOfLines = 0

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....

Swift UITextView with different formatting

Sorry for a basic question, but I'm not sure where to start. Is the following possible in Swift?
In a UITextView (Not a label, as in the possible duplicate), different bits of text having different formatting: for instance, a line of large text in the same UITextView as a line of small text. Here is a mockup of what I mean:
Is this possible in one UITextView?
You should have a look at NSAttributedString. Here's an example of how you could use it:
let largeTextString = "Here is some large, bold text"
let smallTextString = "Here is some smaller text"
let textString = "\n\(largeTextString)\n\n\(smallTextString)"
let attrText = NSMutableAttributedString(string: textString)
let largeFont = UIFont(name: "Arial-BoldMT", size: 50.0)!
let smallFont = UIFont(name: "Arial", size: 30.0)!
// Convert textString to NSString because attrText.addAttribute takes an NSRange.
let largeTextRange = (textString as NSString).range(of: largeTextString)
let smallTextRange = (textString as NSString).range(of: smallTextString)
attrText.addAttribute(NSFontAttributeName, value: largeFont, range: largeTextRange)
attrText.addAttribute(NSFontAttributeName, value: smallFont, range: smallTextRange)
textView.attributedText = attrText
The result: