Styled Text for Labels in your Xojo iOS app

If you like to get styled text on your labels in iOS, you can use our NSAttributedStringMBS class in our MBS Xojo MacCocoa Plugin like below.

As you see we create a NSMutableAttributedStringMBS object for some string and add attributes with zero based ranges there. We then use a declare to setAttributedText to assign the attributed string. Currently our classes for Cocoa controls are not ported to iOS in the plugin, but a quick declare helps us here.

EventHandler Sub Open()
	// create some text from a string. Could also read in RTF
	Dim a As NSAttributedStringMBS = NSAttributedStringMBS.attributedStringWithString("Hello World")
	
	// make a mutable copy
	Dim m As NSMutableAttributedStringMBS = a.mutableCopy
	
	// now add bold font
	Dim r1 As New NSRangeMBS(0,5)
	m.addAttribute(m.NSFontAttributeName, NSFontMBS.boldSystemFontOfSize(13), r1)
	
	// and underline
	Dim r2 As New NSRangeMBS(6,5)
	m.addAttribute(m.NSUnderlineStyleAttributeName, m.NSUnderlineStyleSingle, r2)
	
	// assign new styled text
	Declare Sub setAttributedText Lib "UIKit" Selector "setAttributedText:" (NSTextViewRef As ptr, AttributedStringHandle As Integer )
	
	setAttributedText Label1.Handle, m.Handle
End EventHandler

Not all styled are available on iOS. You can for example use NSForegroundColorAttributeName with NSColorMBS (actually UIColor on iOS internally) to color the text. Since superscript and subscript are not available, you can emulate it with using NSBaselineOffsetAttributeName to change the base line and then use a smaller font for the words.

1 Like
Forum for Xojo Programming Language and IDE. Copyright © 2021 Xojo, Inc.