NSTextAttachment image alignment - ios

I am following this cool tutorial Implementing Rich Text with Images on OS X and iOS by #Duncan Groenewald and was able to display images in my UITextView. However, these images are not centered they way I would like them to be. See image
As you can see, I would like my image to be centered on the X-axis.
I tried returning the rect with appropriate values in -attachmentBoundsForTextContainer:proposedLineFragment:glyphPosition:characterIndex but that did not help.
I also tried setting the NSKernAttributeName for the NSTextAttachment attributed string. But all it did was hide the image some how.

Try setting the paragraph style on your attachment with a center alignment.
If your images are embedded in an attributed string as attachments, you can access them by enumerating through the attributed string's attachment attributes.
For example:
attributedContent.enumerateAttribute(NSAttachmentAttributeName, inRange: NSRange(location: 0, length: attributedContent.length), options: nil) { (attribute, range, stop) -> Void in
if let attachment = attribute as? NSTextAttachment {
// this example assumes you want to center all attachments. You can provide additional logic here. For example, check for attachment.image.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .Center
attributedContent.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: range)
}
}

This is Swift 3.1 using extension:
extension NSMutableAttributedString {
func setAttachmentsAlignment(_ alignment: NSTextAlignment) {
self.enumerateAttribute(NSAttachmentAttributeName, in: NSRange(location: 0, length: self.length), options: .longestEffectiveRangeNotRequired) { (attribute, range, stop) -> Void in
if attribute is NSTextAttachment {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = alignment
self.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: range)
}
}
}
}
In this way you can you easily apply alignment for attachments on attributed string:
let attributeString = NSMutableAttributedString(string: "")
// add attachments
attributeString.setAttachmentsAlignment(.center)

Here's another way how to set the alignment for an NSTextAttachment image. Hopefully this will also help someone struggling with this. I'm using the code below in a func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
var buttonText = "My Button";
let align = NSMutableParagraphStyle();
align.alignment = NSTextAlignment.center;
align.firstLineHeadIndent = 10.0;
align.headIndent = 10.0;
align.tailIndent = -10.0;
let para = NSMutableAttributedString();
// top padding
para.append(NSAttributedString(string: "\n", attributes: [NSParagraphStyleAttributeName: align, NSFontAttributeName: UIFont(name: "Helvetica", size: 10.0)!, NSForegroundColorAttributeName: UIColor.white]));
// image
let img = NSTextAttachment();
img.image = UIImage(named: "MyIcon");
img.bounds = CGRect(x: 0, y: UIFont(name: "Helvetica", size: 18.0)!.descender, width: img.image!.size.width, height: img.image!.size.height);
let nas = NSAttributedString(attachment: img).mutableCopy() as! NSMutableAttributedString;
nas.addAttribute(NSParagraphStyleAttributeName, value: align, range: NSRange(location: 0, length: nas.length));
para.append(nas);
// space to text
buttonText = " " + buttonText;
// text
para.append(NSAttributedString(
string: buttonText,
attributes: [NSParagraphStyleAttributeName: align, NSFontAttributeName: UIFont(name: "Helvetica", size: 18.0)!, NSForegroundColorAttributeName: UIColor.black]));
// bottom padding
para.append(NSAttributedString(string: "\n", attributes: [NSParagraphStyleAttributeName: align, NSFontAttributeName: UIFont(name: "Helvetica", size: 10.0)!, NSForegroundColorAttributeName: UIColor.white]));
// set cell label
let label = cell.textLabel!;
label.numberOfLines = 0;
label.layer.borderWidth = 0;
label.layer.masksToBounds = false;
label.backgroundColor = UIColor.clear;
label.layer.backgroundColor = UIColor.green;
label.attributedText = para;

Related

NSAttributedText alignment right and left doesn't work for the same object

I have a simple extension for NSAttributedString:
convenience init(
string: String,
strikeThrough: Bool = false,
color: UIColor? = nil,
font: UIFont? = nil,
alignment: NSTextAlignment? = nil
) {
var attributes = [NSAttributedString.Key: Any]()
if strikeThrough {
attributes[.strikethroughStyle] = NSUnderlineStyle.single.rawValue
}
if let color = color {
attributes[.foregroundColor] = color
}
if let font = font {
attributes[.font] = font
}
if let alignment = alignment {
let style = NSMutableParagraphStyle()
style.alignment = alignment
attributes[.paragraphStyle] = style
}
self.init(string: string, attributes: attributes)
}
And this is how I use it in code:
let baseString = "Collectives™ helps you find trusted answers faster, engage with product experts, and share knowledge around the technologies you use most."
let baseColor: UIColor.mineShaft
let baseFont = UIFont.poppinsRegular.withSize(16)
let attributedString = NSMutableAttributedString(string: baseString, color: baseColor, font: baseFont)
attributedString.append(NSAttributedString(string: "\n"))
let color = baseColor.withAlphaComponent(0.5)
let font = baseFont.withSize(12)
let originalString = NSAttributedString(string: baseString, color: color, font: font, alignment: .right)
attributedString.append(originalString)
And the results is the following:
Everything is left aligned. Why? The second part should be right aligned.
I set two style for attributes and the result is ok, try to set like this:
let style = NSMutableParagraphStyle()
style.alignment = .left
let style2 = NSMutableParagraphStyle()
style2.alignment = .right
let attributedString = NSMutableAttributedString(string: "Collectives™ helps you find trusted answers faster, engage with product experts, and share knowledge around the technologies you use most.", attributes: [.paragraphStyle: style, .foregroundColor: UIColor.black, .font: UIFont.systemFont(ofSize: 14, weight: .bold)])
attributedString.append(NSAttributedString(string: "\nCollectives™ helps you find trusted answers faster, engage with product experts, and share knowledge around the technologies you use most.", attributes: [.paragraphStyle: style2, .foregroundColor: UIColor.gray, .font: UIFont.systemFont(ofSize: 12, weight: .semibold)]))
yourTextContainer.attributedText = attributedString
The result:

Make half of the TextView's text color Different than other 50% of the text SWIFT

I've got a large text in my UITextView and I want to make the 50% of the text's color red and the other 50% green . I've added NSMutableAttributedString in the TextView but it works's for the full range of the text . How to divide the textView's text into two sections and color them into red and green ?
let strNumber: NSString = self.text as NSString // TextView Text
let range = (strNumber).range(of: strNumber as String)
let attribute = NSMutableAttributedString.init(string: strNumber as String)
attribute.addAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 14) , NSAttributedString.Key.foregroundColor : UIColor.red], range: range)
self.attributedText = attribute
It seems you have an extension to UITextView. The following extension function will make the existing attributed text of a text view be half red and half green. All other existing attributes, if any, will remain.
extension UITextView {
func makeHalfRedGreen() {
if let text = self.text {
let half = text.count / 2
let halfIndex = text.index(text.startIndex, offsetBy: half)
let firstRange = NSRange(..<halfIndex, in: text)
let secondRange = NSRange(halfIndex..., in: text)
let attrTxt = NSMutableAttributedString(attributedString: attributedText)
attrTxt.addAttribute(.foregroundColor, value: UIColor.red, range: firstRange)
attrTxt.addAttribute(.foregroundColor, value: UIColor.green, range: secondRange)
attributedText = attrTxt
}
}
}
Try to use function like below
text_lbl.attributedText = self.decorateText(txt1: "Red Color", txt2: “Blue Color”)
func decorateText(txt1:String, txt2:String)->NSAttributedString{
let textAttributesOne = [NSAttributedStringKey.foregroundColor: UIColor.red, NSAttributedStringKey.font: UIFont(name: "Poppins-Regular", size: 12.0)!] as [NSAttributedStringKey : Any]
let textAttributesTwo = [NSAttributedStringKey.foregroundColor: UIColor.blue, NSAttributedStringKey.font: UIFont(name: "Poppins-SemiBold", size: 14.0)!] as [NSAttributedStringKey : Any]
let textPartOne = NSMutableAttributedString(string: txt1, attributes: textAttributesOne)
let textPartTwo = NSMutableAttributedString(string: txt2, attributes: textAttributesTwo)
let textCombination = NSMutableAttributedString()
textCombination.append(textPartOne)
textCombination.append(textPartTwo)
return textCombination
}

Wrong height for UILabel when using custom lineSpacing and kern

I am getting wrong height for an UILabel if I use NSAttributedString that has custom kern and lineSpacing.
Here is how I set the custom kern and line spacing:
override func viewDidLoad() {
super.viewDidLoad()
let shortText = "Single line"
self.label.attributedText = self.getAttributedText(text: shortText, kern: 0.2, lineSpacing: 8)
self.label2.attributedText = self.getAttributedText(text: shortText, kern: 0, lineSpacing: 8)
}
private func getAttributedText(text: String, kern: CGFloat, lineSpacing: CGFloat) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: text)
let style = NSMutableParagraphStyle()
style.lineSpacing = lineSpacing
let attributes: [NSAttributedStringKey : Any] =
[.paragraphStyle : style,
.kern: kern]
attributedString.addAttributes(attributes,
range: NSMakeRange(0, attributedString.length))
return attributedString
}
And here is what I get:
The first label (the one that has custom kern), has its height wrong. It's exactly 8 points taller than it should be - that's the custom line height that I am using.
This only happens for single line labels. If I use text that is on a couple of lines, it works as expected.
This is a bug with NSAttributedStringKey.kern. As a workaround, you can calculate the number of lines of your UILabel with the suggestions in this answer. If it has one line only, set lineSpacing to 0.
private func getAttributedText(text: String, kern: CGFloat, lineSpacing: CGFloat) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: text)
let font = UIFont.systemFont(ofSize: 16)
let attributes: [NSAttributedStringKey : Any] = [.kern: kern,
.font: font]
attributedString.addAttributes(attributes, range: NSMakeRange(0, attributedString.length))
let maxSize = CGSize(width: [custom width], height: CGFloat.greatestFiniteMagnitude)
let sizeOfLabel = attributedString.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, context: nil)
if sizeOfLabel.height > font.lineHeight {
let style = NSMutableParagraphStyle()
style.lineSpacing = lineSpacing
attributedString.addAttribute(.paragraphStyle, value: style, range: NSMakeRange(0, attributedString.length))
}
return attributedString
}

How to Increase Line spacing in UILabel in Swift

I have a label which has few lines of text and I want to increase the spacing between the lines. There are similar questions asked by others but the solutions don't solve my problems. Also my label may or may not contain paragraphs. I am new to Swift. Is there a solution using storyboard? Or only through NSAttributedString its possible?
Programatically add LineSpacing to your UILabel using following snippet.
Earlier Swift version
let attributedString = NSMutableAttributedString(string: "Your text")
// *** Create instance of `NSMutableParagraphStyle`
let paragraphStyle = NSMutableParagraphStyle()
// *** set LineSpacing property in points ***
paragraphStyle.lineSpacing = 2 // Whatever line spacing you want in points
// *** Apply attribute to string ***
attributedString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
// *** Set Attributed String to your label ***
label.attributedText = attributedString
Swift 4.0
let attributedString = NSMutableAttributedString(string: "Your text")
// *** Create instance of `NSMutableParagraphStyle`
let paragraphStyle = NSMutableParagraphStyle()
// *** set LineSpacing property in points ***
paragraphStyle.lineSpacing = 2 // Whatever line spacing you want in points
// *** Apply attribute to string ***
attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
// *** Set Attributed String to your label ***
label.attributedText = attributedString
Swift 4.2
let attributedString = NSMutableAttributedString(string: "Your text")
// *** Create instance of `NSMutableParagraphStyle`
let paragraphStyle = NSMutableParagraphStyle()
// *** set LineSpacing property in points ***
paragraphStyle.lineSpacing = 2 // Whatever line spacing you want in points
// *** Apply attribute to string ***
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
// *** Set Attributed String to your label ***
label.attributedText = attributedString
From Interface Builder:
Programmatically:
SWift 4 & 4.2
Using label extension
extension UILabel {
func setLineSpacing(lineSpacing: CGFloat = 0.0, lineHeightMultiple: CGFloat = 0.0) {
guard let labelText = self.text else { return }
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing
paragraphStyle.lineHeightMultiple = lineHeightMultiple
let attributedString:NSMutableAttributedString
if let labelattributedText = self.attributedText {
attributedString = NSMutableAttributedString(attributedString: labelattributedText)
} else {
attributedString = NSMutableAttributedString(string: labelText)
}
// (Swift 4.2 and above) Line spacing attribute
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
// (Swift 4.1 and 4.0) Line spacing attribute
attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
Now call extension function
let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
// Pass value for any one argument - lineSpacing or lineHeightMultiple
label.setLineSpacing(lineSpacing: 2.0) . // try values 1.0 to 5.0
// or try lineHeightMultiple
//label.setLineSpacing(lineHeightMultiple = 2.0) // try values 0.5 to 2.0
Or using label instance (Just copy & execute this code to see result)
let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
// Line spacing attribute
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
// Character spacing attribute
attrString.addAttribute(NSAttributedStringKey.kern, value: 2, range: NSMakeRange(0, attrString.length))
label.attributedText = attrString
Swift 3
let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
attrString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
label.attributedText = attrString
You can control the line spacing in storyboard.
Same question.
Recent solution for Swift 5.0
private extension UILabel {
// MARK: - spacingValue is spacing that you need
func addInterlineSpacing(spacingValue: CGFloat = 2) {
// MARK: - Check if there's any text
guard let textString = text else { return }
// MARK: - Create "NSMutableAttributedString" with your text
let attributedString = NSMutableAttributedString(string: textString)
// MARK: - Create instance of "NSMutableParagraphStyle"
let paragraphStyle = NSMutableParagraphStyle()
// MARK: - Actually adding spacing we need to ParagraphStyle
paragraphStyle.lineSpacing = spacingValue
// MARK: - Adding ParagraphStyle to your attributed String
attributedString.addAttribute(
.paragraphStyle,
value: paragraphStyle,
range: NSRange(location: 0, length: attributedString.length
))
// MARK: - Assign string that you've modified to current attributed Text
attributedText = attributedString
}
}
And the usage:
let yourLabel = UILabel()
let yourText = "Hello \n world \n !"
yourLabel.text = yourText
yourLabel.addInterlineSpacing(spacingValue: 1.5)
Swift 4 and Swift 5
extension NSAttributedString {
func withLineSpacing(_ spacing: CGFloat) -> NSAttributedString {
let attributedString = NSMutableAttributedString(attributedString: self)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byTruncatingTail
paragraphStyle.lineSpacing = spacing
attributedString.addAttribute(.paragraphStyle,
value: paragraphStyle,
range: NSRange(location: 0, length: string.count))
return NSAttributedString(attributedString: attributedString)
}
}
How to use
let example = NSAttributedString(string: "This is Line 1 \nLine 2 \nLine 3 ").withLineSpacing(15)
testLabel.attributedText = example
You can use this reusable extension:
extension String {
func lineSpaced(_ spacing: CGFloat) -> NSAttributedString {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = spacing
let attributedString = NSAttributedString(string: self, attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
return attributedString
}
}
Dipen's answer updated for Swift 4
let attr = NSMutableAttributedString(string: today)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 2
attr.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attr.length))
label.attributedText = attr;
extension UILabel {
var spacing: CGFloat {
get {return 0}
set {
let textAlignment = self.textAlignment
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = newValue
let attributedString = NSAttributedString(string: self.text ?? "", attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
self.attributedText = attributedString
self.textAlignment = textAlignment
}
}
}
let label = UILabel()
label.text = "test"
label.spacing = 10
//Swift 4:
func set(text:String,
inLabel:UILabel,
withLineSpacing:CGFloat,
alignment:NSTextAlignment){
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = withLineSpacing
let attrString = NSMutableAttributedString(string: text)
attrString.addAttribute(NSAttributedStringKey.paragraphStyle,
value:paragraphStyle,
range:NSMakeRange(0, attrString.length))
inLabel.attributedText = attrString
inLabel.textAlignment = alignment
}
Create LabelStyle
struct LabelStyle {
let font: UIFont
let fontMetrics: UIFontMetrics?
let lineHeight: CGFloat?
let tracking: CGFloat
init(font: UIFont, fontMetrics: UIFontMetrics? = nil, lineHeight: CGFloat? = nil, tracking: CGFloat = 0) {
self.font = font
self.fontMetrics = fontMetrics
self.lineHeight = lineHeight
self.tracking = tracking
}
func attributes(for alignment: NSTextAlignment, lineBreakMode: NSLineBreakMode) -> [NSAttributedString.Key: Any] {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = alignment
paragraphStyle.lineBreakMode = lineBreakMode
var baselineOffset: CGFloat = .zero
if let lineHeight = lineHeight {
let lineHeightMultiple = lineHeight / font.lineHeight
paragraphStyle.lineHeightMultiple = lineHeightMultiple
baselineOffset = 1 / lineHeightMultiple
let scaledLineHeight: CGFloat = fontMetrics?.scaledValue(for: lineHeight) ?? lineHeight
paragraphStyle.minimumLineHeight = scaledLineHeight
paragraphStyle.maximumLineHeight = scaledLineHeight
}
return [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.kern: tracking,
NSAttributedString.Key.baselineOffset: baselineOffset,
NSAttributedString.Key.font: font
]
}
}
Create custom Label class and use our style
public class Label: UILabel {
var style: LabelStyle? { nil }
public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if previousTraitCollection?.preferredContentSizeCategory != traitCollection.preferredContentSizeCategory {
updateText()
}
}
convenience init(text: String?, textColor: UIColor) {
self.init()
self.text = text
self.textColor = textColor
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
updateText()
}
private func commonInit() {
font = style?.font
adjustsFontForContentSizeCategory = true
}
private func updateText() {
text = super.text
}
public override var text: String? {
get {
guard style?.attributes != nil else {
return super.text
}
return attributedText?.string
}
set {
guard let style = style else {
super.text = newValue
return
}
guard let newText = newValue else {
attributedText = nil
super.text = nil
return
}
let attributes = style.attributes(for: textAlignment, lineBreakMode: lineBreakMode)
attributedText = NSAttributedString(string: newText, attributes: attributes)
}
}
}
Create concrete Label
public final class TitleLabel {
override var style: LabelStyle? {
LabelStyle(
font: UIFont.Title(),
lineHeight: 26.21,
tracking: 0.14
)
}
}
and use it
#IBOutlet weak var titleLabel: TitleLabel!
In addition to using attributed strings & paragraph styles, for small adjustemnts, font descriptors can also come in handy.
For instance:
let font: UIFont = .init(
descriptor: UIFontDescriptor
.preferredFontDescriptor(withTextStyle: .body)
.withSymbolicTraits(.traitLooseLeading)!,
size: 0
)
This will create a font with a looser leading, resulting in a text with a slightly larger line height (it adds 2 points) than the default system font. traitTightLeading can also be used for the opposite effect (it reduces the leading of the font by 2 points).
I wrote a blog post comparing the approaches here: https://bootstragram.com/blog/line-height-with-uikit/.
This solution worked for swift 5
this is reference to answer of https://stackoverflow.com/a/62116213/13171606
I Made some changes for "NSMutableAttributedString" and included the full example, i think it will help u all
Note: Please Adjust Color and Font style if found any error.
Extension
extension NSAttributedString {
func withLineSpacing(_ spacing: CGFloat) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(attributedString: self)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byTruncatingTail
paragraphStyle.lineSpacing = spacing
attributedString.addAttribute(.paragraphStyle,
value: paragraphStyle,
range: NSRange(location: 0, length: string.count))
return NSMutableAttributedString(attributedString: attributedString)
}
}
Implementation Example
let myAttributedText = NSMutableAttributedString(string: "Please enter the required details to change your AAAAAAAAA AAAAA AAAAA. Maximum AAAAA can be AAA AA AAA AA.\n\nNote: If you do not have a AAAAA AAAA then please AAAAAAA us at 111-111-111 or send us an email AAAA AAAA AAA AAAAAAAAAA AAAAA address at xxxxxxxxxxxxxxxxxxxxxxxxxxxx.", attributes: [
.font: UIFont.systemFont(ofSize: 14),
.foregroundColor: UIColor.gray,
.kern: 0.0]).withLineSpacing(8)
myAttributedText.addAttributes([
.font: UIFont.systemFont(ofSize: 14),
.foregroundColor: UIColor.blue],
range: NSRange(location: 174, length: 11))
myAttributedText.addAttributes([
.font: UIFont.systemFont(ofSize: 14),
.foregroundColor: UIColor.blue],
range: NSRange(location: 248, length: 28))
UILable
let myLabel: UILabel = {
let label = UILabel()
label.textAlignment = .left
label.numberOfLines = 0
label.attributedText = myAttributedText //Here is your Attributed String
return label
}()

Attributed text with two text alignments

Does anyone know how to achieve two different text alignments in one string?
This is what I want the textView to show:
label value
My code:
let txtView = cell.viewWithTag(77) as! UITextView
let leftStyle = NSMutableParagraphStyle()
leftStyle.alignment = NSTextAlignment.Left
let rightStyle = NSMutableParagraphStyle()
rightStyle.alignment = NSTextAlignment.Right
let attText = NSMutableAttributedString(string: "label", attributes: [NSParagraphStyleAttributeName: leftStyle])
attText.appendAttributedString(NSAttributedString(string: " "))
attText.appendAttributedString(NSAttributedString(string: "value", attributes: [NSParagraphStyleAttributeName: rightStyle]))
txtView.attributedText = attText
What I get instead:
label value
Using NSMutableParagraphStyle with NSTextTab:
let paragraph = NSMutableParagraphStyle()
paragraph.tabStops = [
NSTextTab(textAlignment: .Right, location: 100, options: [:]),
]
let str = "Label\tValue\n"
+ "foo\tbar\n"
let attributed = NSAttributedString(
string: str,
attributes: [NSParagraphStyleAttributeName: paragraph]
)
let view = UITextView(frame: CGRectMake(0, 0, 120, 120))
view.textContainer.lineFragmentPadding = 10
view.attributedText = attributed
Of course, this aligns to "tabstop", but not to the edge of UITextView. When you modify the size of the view, you have to also modify the location of NSTextTab.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
let cell = Placestableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath);
//first text
let attributestitle = [NSAttributedStringKey.font:
UIFont(name: "Helvetica-Bold", size: 15.0)!,
NSAttributedStringKey.foregroundColor: UIColor.black] as [NSAttributedStringKey: Any]
//second text
let attributedString = NSMutableAttributedString(string: "\t"+String(places[indexPath.row].distance!)+" miles", attributes: [NSAttributedStringKey.font: UIFont(name: "Helvetica-Bold", size: 8.0)!,NSAttributedStringKey.foregroundColor: UIColor.black])
let myParagraphStyle = NSMutableParagraphStyle()
myParagraphStyle.alignment = .right
myParagraphStyle.tabStops = [
NSTextTab(textAlignment: .right, location: 300, options: [:]),
]
let attributedStringtitle = NSMutableAttributedString(string: places[indexPath.row].title!, attributes: attributestitle)
//adding the right alignment to the second text alone
attributedString.addAttributes([.paragraphStyle: myParagraphStyle], range: NSRange(location: 0, length: attributedString.length))
//combining two texts with different alignments.
let combination = NSMutableAttributedString()
combination.append(attributedStringtitle)
combination.append(attributedString)
cell.textLabel?.attributedText = combination
return cell;
}

Resources