center and bold TextView swift - swift

Hi all I am trying to set a bold and centre to my text view I have 3 different colours in the view but I want the 2 colours that change to be centred. Is there a way to do this? below is my code.
let myString:String = DisplayableContents.texts[10]
var myMutableString = NSMutableAttributedString()
myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont(name: "Calibri", size: 17.0)!])
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSRange(location:74, length:96))
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.gray, range: NSRange(location:96, length:19))
// set label Attribute
infoBox.attributedText = myMutableString

Try with
let myString:String = DisplayableContents.texts[10]
var myMutableString = NSMutableAttributedString()
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.Center
myMutableString = NSMutableAttributedString(string: myString, attributes: [NSParagraphStyleAttributeName:paragraphStyle, NSFontAttributeName:UIFont(name: "Calibri", size: 17.0)!])
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSRange(location:74, length:96))
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.gray, range: NSRange(location:96, length:19))
// set label Attribute
infoBox.attributedText = myMutableString
But 'Calibri' doesn't exist in iOS. You can check fonts in http://iosfonts.com/. If you are adding the font to your project check its bold variation, probably 'Calibri-Bold'

Related

CIAttributedTextImageGenerator filter - text doesn't fit (NSAttributedString)

I use a Core Image filter CIAttributedTextImageGenerator to generate text as a CIImage. However, sometimes the text just doesn't fit into the resulted CIImage as you can see at the picture:
I tried to play with different key-values of NSAttributedString to make some padding around text but with no success:
func generateImageFromText(_ text: String, style: TextStyle) -> CIImage? {
let font = UIFont.init(name: style.fontName, size: style.fontSize)!
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = style.textAlignment
paragraphStyle.headIndent = 5.0
paragraphStyle.tailIndent = -5.0
paragraphStyle.firstLineHeadIndent = 0
let shadow = NSShadow()
if let shadowStyle = style.shadowStyle {
shadow.shadowColor = shadowStyle.color
shadow.shadowOffset = shadowStyle.offset
shadow.shadowBlurRadius = shadowStyle.blurRadius
}
var strokeColor = UIColor.clear
var strokeWidth: CGFloat = 0.0
if let strokeStyle = style.strokeStyle {
strokeColor = strokeStyle.color
strokeWidth = strokeStyle.width
}
let attributes: [NSAttributedString.Key: Any] = [
.baselineOffset: 50,
.font: font,
.foregroundColor: style.color,
.paragraphStyle: paragraphStyle,
.shadow: shadow,
.strokeColor: strokeColor,
.strokeWidth: strokeWidth
]
let attributedQuote = NSAttributedString(string: text, attributes: attributes)
let textGenerationFilter = CIFilter(name: "CIAttributedTextImageGenerator")!
textGenerationFilter.setValue(attributedQuote, forKey: "inputText")
textGenerationFilter.setValue(NSNumber(value: Double(1.0)), forKey: "inputScaleFactor")
guard let textImage = textGenerationFilter.outputImage else {
return nil
}
return textImage
}
Maybe there are some values of NSAttributedString that I miss which can help to fit in the text?

Add a label after a String

I need to create a line of text with two colors
There will Be a text, which is string in black and there will be one $ Symbol and it should be red.
lazy var dollarSmb: UILabel = {
let smb = UILabel()
smb.text = "$"
smb.font = UIFont.systemFont(ofSize: 17, weight: .regular)
smb.textColor = UIColor.red
smb.baselineAdjustment = .alignCenters
smb.translatesAutoresizingMaskIntoConstraints = false
return smb
}()
And I want to add it after the label string, something like that:
Var label = "This is a test" + " \(dollarSmb)"
It's not working
Could anyone help me the best way to do that?
Many thanks
You could use NSAttributedString to construct a single string with a different color.
let attributedString = NSMutableAttributedString(string: "This is a test ")
let dollarSymbl = NSAttributedString(string: "$", attributes: [.foregroundColor: UIColor.red])
attributedString.append(dollarSymbl)
// Then assign it to a UILabel
label.attributedText = attributedString
Use an NSAttributedString and instead of setting smb.text, set smb.attributedText.
Something like
smb.attributedText = NSAttributedString(string: "$", attributes [.foregroundColor: UIColor.red])

Discrepancy when calculating geometrical size of string

Why are the results of NSAttributedString.size() and NSLayoutManager.boundingRect(forGlyphRange:in:).size so different?
Example code:
let attrs: [NSAttributedString.Key: Any] = [.font: NSFont.systemFont(ofSize: 14.0)]
let container = NSTextContainer()
container.lineFragmentPadding = 0.0
container.lineBreakMode = .byClipping
container.containerSize = NSSize(width: 5e6, height: 5e6)
let layoutManager = NSLayoutManager()
layoutManager.addTextContainer(container)
let text = NSTextStorage()
text.addLayoutManager(layoutManager)
text.setAttributedString(NSAttributedString(string: "Hello, world!", attributes: attrs))
var range = NSMakeRange(0, text.length)
print(text.size())
print(layoutManager.boundingRect(forGlyphRange: range, in: container).size)
text.setAttributedString(NSAttributedString(string: "東京", attributes: attrs))
range = NSMakeRange(0, text.length)
print(text.size())
print(layoutManager.boundingRect(forGlyphRange: range, in: container).size)
Here's the result I get:
(80.3837890625, 18.0)
(80.3837890625, 17.0)
(25.85410895660203, 14.0)
(25.85410895660203, 19.463557481765747)
As you can see, although the widths are the same, the heights are not. In the first case the NSLayoutManager reports a smaller height than NSAttributedString, and in the second case a larger one.
What accounts for this difference?
I have read the documentation for these two methods. I have also read the Text System Storage Layer Overview in Apple's archive. I could not find the information there.

Swift: Can I adjust attributed text with dynamic font size?

I'm working with the collectionView
whose each cell has the content like this:
everything works pretty well until I test it on an iphone 5s:
"Ho Chi Minh City" was out of bounds.
Here is my code:
func configureNameLabel() {
nameLabel.numberOfLines = 2
let attributedText = NSMutableAttributedString(string: post?.name ?? "", attributes: [.font: UIFont.boldSystemFont(ofSize: 15)])
attributedText.append(NSAttributedString(string: "\nSaturday, December 1, 2018 ⦁ Ho Chi Minh City ⦁ ", attributes:
[.foregroundColor: UIColor.lightGray, .font: UIFont.preferredFont(forTextStyle: .caption1)]))
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 5
attributedText.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedText.string.count))
let attachment = NSTextAttachment()
attachment.image = UIImage(named: "user-male")
attachment.bounds = CGRect(x: 0, y: -2, width: 12, height: 12)
attributedText.append(NSAttributedString(attachment: attachment))
nameLabel.attributedText = attributedText
}
I think this problem is due to the font size, can anybody fix this ?
Thanks guys, I solved it. "label.numberOfLines = 0" worked. the problem is at my constraints.

SKLabelNode Border and Bounds Issue

I am attempting to create text that has an outline. I am currently using SKLabelNode with NSAttributedString, which you can now do in SpriteKit as of iOS 11. The problem is, if the stroke width is too thick, then the outline gets cut off by what appears to be the bounding rectangle of the SKLabelNode. Please see below for the image and code.
extension SKLabelNode {
func addStroke(_ strokeColor:UIColor) {
let font = UIFont(name: self.fontName!, size: self.fontSize)
let attributes:[NSAttributedStringKey:Any] = [.strokeColor: strokeColor, .strokeWidth: 20.0, .font: font!]
let attributedString = NSMutableAttributedString(string: " \(self.text!) ", attributes: attributes)
let label1 = SKLabelNode()
label1.horizontalAlignmentMode = self.horizontalAlignmentMode
label1.text = self.text
label1.zPosition = -1
label1.attributedText = attributedString
self.addChild(label1)
}
}
I looked at expanding the frame of the SKLabelNode serving as the border text, but that is a get-only property. I tried to add leading/trailing spaces, but they appear to be automatically trimmed. Using a negative value for strokeWidth works but creates an inner stroke, I'd prefer to have an outer stroke.
Any ideas? Thanks in advance for the help!
Mike
You shouldn't need to create a separate node for the stroke.
Use negative width values to only render the stroke without fill.
Use .foregroundColor to fill.
You should first check to see if an attributed string is already present to ensure you do not clobber it.
Here is the code:
extension SKLabelNode {
func addStroke(color:UIColor, width: CGFloat) {
guard let labelText = self.text else { return }
let font = UIFont(name: self.fontName!, size: self.fontSize)
let attributedString:NSMutableAttributedString
if let labelAttributedText = self.attributedText {
attributedString = NSMutableAttributedString(attributedString: labelAttributedText)
} else {
attributedString = NSMutableAttributedString(string: labelText)
}
let attributes:[NSAttributedStringKey:Any] = [.strokeColor: color, .strokeWidth: -width, .font: font!, .foregroundColor: self.fontColor!]
attributedString.addAttributes(attributes, range: NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}