Heloo.. I am newbie here for ios, swift and xcode...
I have logic in swift file like:
class ExpandableHeaderView: UITableViewHeaderFooterView {
func customInit(menu: Menu, section: Int, delegate: ExpandableHeaderViewDelegate) {
//Create Attachment
let imageAttachment = NSTextAttachment()
var textAfterIcon: NSMutableAttributedString
switch menu {
case .HOME:
imageAttachment.image = UIImage(named:"home")
textAfterIcon = NSMutableAttributedString(string: " Home")
:
}
//Set bound to reposition
let imageOffsetY:CGFloat = -3.0;
imageAttachment.bounds = CGRect(
x: 0,
y: imageOffsetY,
width: imageAttachment.image!.size.width,
height: imageAttachment.image!.size.height)
//Create string with attachmen
let attachmentString = NSAttributedString(attachment: imageAttachment)
//Initialize mutable string
let completeText = NSMutableAttributedString(string: "")
//Add image to mutable string
completeText.append(attachmentString)
//Add your text to mutable string
completeText.append(textAfterIcon)
self.textLabel?.lineBreakMode = NSLineBreakMode.byTruncatingTail
self.textLabel?.attributedText = completeText
:
}
}
But I got result like:
I have added for all NSLineBreakMode.by*, but no one it is prefect to show image and the label: [image] Home
How can I remove 3 dots in the end for textLabel?.attributedText?
It was really confused me...
So, it is my pleasure for anyone can help me...
env:
xCode v. 9.3
I would not consider truncating your labels by "..." as a problem. You should firstly resolve correct sizing of your labels.
Related
I am wanting to add extra info onto some of the images I add to my UITextView. The class is NSTextAttachment(). I need my images to have some String descriptions so the app knows what's inside the image. How do I add this extra functionality? Is it through an Extension?
let attachment = NSTextAttachment()
attachment.image = image
attachment.bounds = CGRect(origin: .zero, size: image.size)
// Extra properties wanted
attachment.description = "add in info about what is in attachment"
attachment.moreInfo = "some more info about the attachment"
class EmojiTextAttachment:NSTextAttachment{
}
private var EmotagAssociationKey:String? = nil
extension EmojiTextAttachment{
var emoticonName:String?{
get {return objc_getAssociatedObject(self,&EmotagAssociationKey) as? String ?? ""}
set {objc_setAssociatedObject(self, &EmotagAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN) }
}
}
It's been a while, but my solution is up.
Extends NSTextAttachment
You can add parameters with objc_getAssociatedObject and objc_setAssociatedObject
When using it, use EmojiTextAttachment instead of NSTextAttachment.
let emoticon:EmojiTextAttachment = EmojiTextAttachment()
let image = UIImage(named: myImage) as UIImage!
emoticon.image = image?.resizeSelf(newWidth, newHeight)
emoticon.emoticonName = emoname
The docs of objc_getAssociatedObject https://developer.apple.com/documentation/objectivec/1418865-objc_getassociatedobject
I have buttons filled with Colors: enter image description here
When user press on a color, a string is generated, i.e.
Yellow or Blue or Black etc.
What i want is to load the string into a UIColor when i segue back:
garageNameLabel.backgroundColor = UIColor."THE STRING THAT WAS GENERATED"
I know that UIColor.whiteColor(), blackColor() is there.
code:
let theStringColor = Blue
garageNameLabel.backgroundColor = UIColor.theStringColor
Thanks
I solved the problem by making a dictionary
var colors : [String:UIColor] = ["White": UIColor.whiteColor(), "Black":
UIColor.blackColor(), "Gray": UIColor.grayColor(),"Turquoise":
UIColor.cyanColor(),"Red":
UIColor.redColor(),"Yellow":UIColor.yellowColor(),"Blue": UIColor.blueColor(),
"Green": UIColor.greenColor()]
and then loading the string into it i.e.:
let theStringColor = "Blue"
garageNameLabel.backgroundColor = colors[theStringColor]
In OBJC code like this works. i have not tested this code, only translated it from OBJC to swift.
private func setColorWithNameForLabel(label: UILabel, colorName: String) {
let colorString = colorName + "Color" // if your colorName matches f.i. "black" --> blackColor
let s = Selector(colorString)
if let color = UIColor.performSelector(s).takeUnretainedValue() as? UIColor { // as of swift 2.0 you have to take the retained value
label.textColor = color
}
}
You can pass a parameter in the segue. In the new view, in the viewDidLoad () function, you can perform a check that change color depending on the value of the parameter.
if parameter == "blue" {
garageNameLabel.backgroundColor = UIColor.blueColor ()
} Else if parameter == "green" {
garageNameLabel.backgroundColor = UIColor.greenColor ()
}
I want to Set Particular Word clickable in UILabel text using Swift.
Is it possible?
If more than one label is here how can I detect which word is pressed?
You can not do with the simple label.
There is library available in the github.
https://github.com/TTTAttributedLabel/TTTAttributedLabel
From this you can use the method called yourLabel.addLinkToURL()
class ViewController: UIViewController , TTTAttributedLabelDelegate{
#IBOutlet var lbl: TTTAttributedLabel!
override func viewDidLoad() {
super.viewDidLoad()
var str : NSString = "Hello this is link"
lbl.delegate = self
lbl.text = str as String
var range : NSRange = str.rangeOfString("link")
lbl.addLinkToURL(NSURL(string: "http://github.com/mattt/")!, withRange: range)
}
func attributedLabel(label: TTTAttributedLabel!, didSelectLinkWithURL url: NSURL!) {
UIApplication.sharedApplication().openURL(url)
}
}
SWIFT 3.0
privacyLabel.delegate = self
let strPolicy : NSString = "Agree to the Terms & Conditions"
privacyLabel.text = strPolicy as String
let range1 : NSRange = strPolicy.range(of: "Terms & Conditions")
privacyLabel.addLink(to: URL(string: "http://Terms.com")!, with: range1)
func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith url: URL!) {
print("url \(url)")
// UIApplication.sharedApplication().openURL(url)
}
I'd like to share my library https://github.com/psharanda/Atributika
It contains modern replacement of TTTAtributedLabel + powerful set of methods to detect and style different stuff like tags, hashtags, mentions etc (everything of that can be clickable)
Some code to show how it works:
let link = Style
.font(.boldSystemFont(ofSize: 14))
.foregroundColor(.black)
.foregroundColor(.red, .highlighted)
let tos = link.named("tos")
let pp = link.named("pp")
let all = Style
.font(.systemFont(ofSize: 14))
.foregroundColor(.gray)
let text = "<tos>Terms of Service</tos> and <pp>Privacy Policy</pp>"
.style(tags: tos, pp)
.styleAll(all)
let tosLabel = AttributedLabel()
tosLabel.textAlignment = .center
tosLabel.attributedText = text
tosLabel.onClick = { label, detection in
switch detection.type {
case .tag(let tag):
switch tag.name {
case "pp":
print("Privacy Policy clicked")
case "tos":
print("Terms of Service clicked")
default:
break
}
default:
break
}
}
view.addSubview(tosLabel)
I am currently trying to display some text in Japanese on a UITextView. Is it possible to display the furigana above the kanji (like below) in a manner similar to the < rt> tag in html, without using a web view?
A lot of text processing is involved, therefore I cannot simply use a web view. In iOS8, CTRubyAnnotationRef was added but there is no documentation (I would welcome any example), and I am also concerned with the lack of compatibility with iOS7. I thought that it would be possible to display the furigana above with the use of an NSAttributedString, but couldn't as of yet.
Update Swift 5.1
This solution is an update of preview answers and let you write Asian sentences with Phonetic Guide, using a pattern in the strings.
Let's start from handling string.
these 4 extension let you to inject in a string the ruby annotation.
the function createRuby() check the string a pattern, that it is: |word written in kanji《phonetic guide》.
Examples:
|紅玉《ルビー》
|成功《せいこう》するかどうかは、きみの|努力《どりょく》に|係《かか》る。
and so on.
the important thing is to follow the pattern.
extension String {
// 文字列の範囲
private var stringRange: NSRange {
return NSMakeRange(0, self.utf16.count)
}
// 特定の正規表現を検索
private func searchRegex(of pattern: String) -> NSTextCheckingResult? {
do {
let patternToSearch = try NSRegularExpression(pattern: pattern)
return patternToSearch.firstMatch(in: self, range: stringRange)
} catch { return nil }
}
// 特定の正規表現を置換
private func replaceRegex(of pattern: String, with templete: String) -> String {
do {
let patternToReplace = try NSRegularExpression(pattern: pattern)
return patternToReplace.stringByReplacingMatches(in: self, range: stringRange, withTemplate: templete)
} catch { return self }
}
// ルビを生成
func createRuby() -> NSMutableAttributedString {
let textWithRuby = self
// ルビ付文字(「|紅玉《ルビー》」)を特定し文字列を分割
.replaceRegex(of: "(|.+?《.+?》)", with: ",$1,")
.components(separatedBy: ",")
// ルビ付文字のルビを設定
.map { component -> NSAttributedString in
// ベース文字(漢字など)とルビをそれぞれ取得
guard let pair = component.searchRegex(of: "|(.+?)《(.+?)》") else {
return NSAttributedString(string: component)
}
let component = component as NSString
let baseText = component.substring(with: pair.range(at: 1))
let rubyText = component.substring(with: pair.range(at: 2))
// ルビの表示に関する設定
let rubyAttribute: [CFString: Any] = [
kCTRubyAnnotationSizeFactorAttributeName: 0.5,
kCTForegroundColorAttributeName: UIColor.darkGray
]
let rubyAnnotation = CTRubyAnnotationCreateWithAttributes(
.auto, .auto, .before, rubyText as CFString, rubyAttribute as CFDictionary
)
return NSAttributedString(string: baseText, attributes: [kCTRubyAnnotationAttributeName as NSAttributedString.Key: rubyAnnotation])
}
// 分割されていた文字列を結合
.reduce(NSMutableAttributedString()) { $0.append($1); return $0 }
return textWithRuby
}
}
Ruby Label: the big problem
As you maybe know, Apple has introduced in iOS 8 the ruby annotation like attribute for the attributedString, and if you did create the the attributed string with ruby annotation and did:
myLabel.attributedText = attributedTextWithRuby
the label did shows perfectly the string without problem.
From iOS 11, Apple unfortunately has removed this feature and, so, if want to show ruby annotation you have override the method draw, to effectively draw the text. To do this, you have to use Core Text to handle the text hand it's lines.
Let's show the code
import UIKit
public enum TextOrientation { //1
case horizontal
case vertical
}
class RubyLabel: UILabel {
public var orientation:TextOrientation = .horizontal //2
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
// ルビを表示
override func draw(_ rect: CGRect) {
//super.draw(rect) //3
// context allows you to manipulate the drawing context (i'm setup to draw or bail out)
guard let context: CGContext = UIGraphicsGetCurrentContext() else {
return
}
guard let string = self.text else { return }
let attributed = NSMutableAttributedString(attributedString: string.createRuby()) //4
let path = CGMutablePath()
switch orientation { //5
case .horizontal:
context.textMatrix = CGAffineTransform.identity;
context.translateBy(x: 0, y: self.bounds.size.height);
context.scaleBy(x: 1.0, y: -1.0);
path.addRect(self.bounds)
attributed.addAttribute(NSAttributedString.Key.verticalGlyphForm, value: false, range: NSMakeRange(0, attributed.length))
case .vertical:
context.rotate(by: .pi / 2)
context.scaleBy(x: 1.0, y: -1.0)
//context.saveGState()
//self.transform = CGAffineTransform(rotationAngle: .pi/2)
path.addRect(CGRect(x: self.bounds.origin.y, y: self.bounds.origin.x, width: self.bounds.height, height: self.bounds.width))
attributed.addAttribute(NSAttributedString.Key.verticalGlyphForm, value: true, range: NSMakeRange(0, attributed.length))
}
attributed.addAttributes([NSAttributedString.Key.font : self.font], range: NSMakeRange(0, attributed.length))
let frameSetter = CTFramesetterCreateWithAttributedString(attributed)
let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0,attributed.length), path, nil)
// Check need for truncate tail
//6
if (CTFrameGetVisibleStringRange(frame).length as Int) < attributed.length {
// Required truncate
let linesNS: NSArray = CTFrameGetLines(frame)
let linesAO: [AnyObject] = linesNS as [AnyObject]
var lines: [CTLine] = linesAO as! [CTLine]
let boundingBoxOfPath = path.boundingBoxOfPath
let lastCTLine = lines.removeLast() //7
let truncateString:CFAttributedString = CFAttributedStringCreate(nil, "\u{2026}" as CFString, CTFrameGetFrameAttributes(frame))
let truncateToken:CTLine = CTLineCreateWithAttributedString(truncateString)
let lineWidth = CTLineGetTypographicBounds(lastCTLine, nil, nil, nil)
let tokenWidth = CTLineGetTypographicBounds(truncateToken, nil, nil, nil)
let widthTruncationBegins = lineWidth - tokenWidth
if let truncatedLine = CTLineCreateTruncatedLine(lastCTLine, widthTruncationBegins, .end, truncateToken) {
lines.append(truncatedLine)
}
var lineOrigins = Array<CGPoint>(repeating: CGPoint.zero, count: lines.count)
CTFrameGetLineOrigins(frame, CFRange(location: 0, length: lines.count), &lineOrigins)
for (index, line) in lines.enumerated() {
context.textPosition = CGPoint(x: lineOrigins[index].x + boundingBoxOfPath.origin.x, y:lineOrigins[index].y + boundingBoxOfPath.origin.y)
CTLineDraw(line, context)
}
}
else {
// Not required truncate
CTFrameDraw(frame, context)
}
}
//8
override var intrinsicContentSize: CGSize {
let baseSize = super.intrinsicContentSize
return CGSize(width: baseSize.width, height: baseSize.height * 1.0)
}
}
Code explanation:
1- Chinese and japanese text can be written in horizontal and vertical way. This enumeration let you switch in easy way between horizontal and vertical orietantation.
2- public variable with switch orientation text.
3- this method must be commented. the reason is that call it you see two overlapping strings:one without attributes, last your attributed string.
4- here call the method of String class extension in which you create the attributed string with ruby annotation.
5- This switch, rotate if need the context in which draw your text in case you want show vertical text. In fact in this switch you add the attribute NSAttributedString.Key.verticalGlyphForm that in case vertical is true, false otherwise.
6- This 'if' is particular important because, the label, cause we had commented the method 'super.draw()' doesn't know how to manage a long string. without this 'if', the label thinks to have only one line to draw. And so, you still to have a string with '...' like tail. In this 'if' the string is broken in more line and drawing correctly.
7- When you don't give to label some settings, the label knows to have more one line but because it can't calculate what is the showable last piece of string, give error in execution time and the app goes in crash. So be careful. But, don't worry! we talk about the right settings to give it later.
8- this is very important to fit the label to text's size.
How to use the RubyLabel
the use of the label is very simple:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var rubyLabel: RubyLabel! //1
override func viewDidLoad() {
super.viewDidLoad()
setUpLabel()
}
private func setUpLabel() {
rubyLabel.text = "|成功《せいこう》するかどうかは、きみの|努力《どりょく》に|係《かか》る。|人々《ひとびと》の|生死《せいし》に|係《かか》る。" //2
//3
rubyLabel.textAlignment = .left
rubyLabel.font = .systemFont(ofSize: 20.0)
rubyLabel.orientation = .horizontal
rubyLabel.lineBreakMode = .byCharWrapping
}
}
Code Explanation:
1- connect label to xib if use storyboard or xib file or create label.
2- as I say, the use is very simple: here assign the string with ruby pattern like any other string
3- these setting are the setting to have to set to make work the label. You can set via code or via storyboard/xib
Be careful
if you use storyboard/xib, if you don't put correctly the constraints, the label give you the error at point n° 7.
Result
Works, but not perfect
As you can see by screenshot, this label work well but still has some problem.
1- with vertical text the label still in horizontal shape;
2- if the string contains \n to split the string in more lines, the label shows only the number of lines that the string would have had if was without the '\n' character.
I'm working for fix these problem, but your help is appreciated.
In the end I created a function that gets the kanji's position and create labels every time, above the kanji. It's quite dirty but it's the only way to insure a compatibility with iOS7.
However I have to mention the remarkable examples that you can find on GitHub for the CTRubyAnnotationRef nowadays like : http://dev.classmethod.jp/references/ios8-ctrubyannotationref/
and
https://github.com/shinjukunian/SimpleFurigana
Good luck to all of you !
Here's a focused answer with some comments. This works for UITextView and UILabel on iOS 16.
let rubyAttributes: [CFString : Any] = [
kCTRubyAnnotationSizeFactorAttributeName : 0.5,
kCTRubyAnnotationScaleToFitAttributeName : 0.5,
]
let annotation = CTRubyAnnotationCreateWithAttributes(
.center, // Alignment relative to base text
.auto, // Overhang for adjacent characters
.before, // `before` = above, `after` = below, `inline` = after the base text (for horizontal text)
"Ruby!" as CFString,
rubyAttributes as CFDictionary
)
let stringAttributes = [kCTRubyAnnotationAttributeName as NSAttributedString.Key : annotation]
NSAttributedString(string: "Base Text!", attributes: stringAttributes)
Note, you may want to UITextView.textContainerInset.top to something larger than the default to avoid having the ruby clipped by the scrollview.
I have a NSAttributedString to which I am adding a NSTextAttachment. The image is 50w by 50h but I'd like it to scale down to reflect the line height of the attributed string. I thought this would be done automatically but I guess not. I have looked at the UImage class reference but this image doesn't seem to be set in a UIImageView so no access to a frame property. Here's a screenshot of what I currently have:
In an ideal world, I would also like to implement a way to scale up the image based upon user input (such as increasing the font size). Any ideas on how to achieve this?
thx
edit 1
here's how I'm creating it:
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:#"note-small.png"];
NSLog(#"here is the scale: %f", textAttachment.image.scale);
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
[headerAS replaceCharactersInRange:NSMakeRange([headerAS length], 0) withString:#" "];
[headerAS replaceCharactersInRange:NSMakeRange([headerAS length], 0) withAttributedString:attrStringWithImage];
You should set bounds form attachment to resize image like this:
attachment.bounds = CGRectMake(0, 0, yourImgWidth, yourImgHeight)
If you need to resize a bunch of NSTextAttachment images while keeping their aspect ratio i've written a handy extension: http://hack.swic.name/convenient-nstextattachment-image-resizing
extension NSTextAttachment {
func setImageHeight(height: CGFloat) {
guard let image = image else { return }
let ratio = image.size.width / image.size.height
bounds = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: ratio * height, height: height)
}
}
Example usage:
let textAttachment = NSTextAttachment()
textAttachment.image = UIImage(named: "Image")
textAttachment.setImageHeight(16) // Whatever you need to match your font
let imageString = NSAttributedString(attachment: textAttachment)
yourAttributedString.appendAttributedString(imageString)
Look at subclassing NSTextAttachment and implementing the NSTextAttachmentContainer methods to return different sizes based on the text container supplied. By default, NSTextAttachment just returns the size of the image it is provided with.
Swift4
if you want a attributed string along with the image or a icon
here you can do something like this.
func AttributedTextwithImgaeSuffixAndPrefix(AttributeImage1 : UIImage , AttributedText : String ,AttributeImage2 : UIImage, LabelBound : UILabel) -> NSMutableAttributedString
{
let fullString = NSMutableAttributedString(string: " ")
let image1Attachment = NSTextAttachment()
image1Attachment.bounds = CGRect(x: 0, y: ((LabelBound.font.capHeight) - AttributeImage1.size.height).rounded() / 2, width: AttributeImage1.size.width, height: AttributeImage1.size.height)
image1Attachment.image = AttributeImage1
let image1String = NSAttributedString(attachment: image1Attachment)
let image2Attachment = NSTextAttachment()
image2Attachment.bounds = CGRect(x: 0, y: ((LabelBound.font.capHeight) - AttributeImage2.size.height).rounded() / 2, width: AttributeImage2.size.width, height: AttributeImage2.size.height)
image2Attachment.image = AttributeImage2
let image2String = NSAttributedString(attachment: image2Attachment)
fullString.append(image1String)
fullString.append(NSAttributedString(string: AttributedText))
fullString.append(image2String)
return fullString
}
you can use this code as mentioned below:
self.lblMid.attributedText = AttributedTextwithImgaeSuffixAndPrefix(AttributeImage1: #imageLiteral(resourceName: "Left") , AttributedText: " Payment Details ", AttributeImage2: #imageLiteral(resourceName: "RIght") , LabelBound: self.lblMid)
here you can add images you can replace it with your own:
Left Image
Right Image
Out put will be like this
NSTextAtatchment is just a holder for a UIImage so scale the image when it needs scaling and recreate the text attachment or set it's image. You'll need to force a nslayout update if you change the image on an existing text attachment.
Thanks #Dung Nguyen, for his answer. I found that his solution works well on iOS devices, but not working on macOS when trying to update an attachment in a large NSAttributedString. So I searched for my own solution for that. Here it is
let newSize: NSSize = \\ the new size for the image attachment
let originalAttachment: NSTextAttachment = \\ wherever the attachment comes from
let range: NSRange = \\ the range of the original attachment in a wholeAttributedString object which is an NSMutableAttributedString
if originalAttachment.fileWrapper != nil,
originalAttachment.fileWrapper!.isRegularFile {
if let contents = originalAttachment.fileWrapper!.regularFileContents {
let newAttachment = NSTextAttachment()
newAttachment.image = NSImage(data: contents)
#if os(iOS)
newAttachment.fileType = originalAttachment.fileType
newAttachment.contents = originalAttachment.contents
newAttachment.fileWrapper = originalAttachment.fileWrapper
#endif
newAttachment.bounds = CGRect(x: originalAttachment.bounds.origin.x,
y: originalAttachment.bounds.origin.y,
width: newSize.width, height: newSize.height)
let newAttachmentString = NSAttributedString(attachment: newAttachment)
wholeAttributedString.replaceCharacters(in: range, with: newAttachmentString)
}
}
Also, on different OS, the image size or bounds an image attachment returns can be different. In order to extract the correct image size, I wrote the following extensions:
extension FileWrapper {
func imageSize() -> CPSize? {
if self.isRegularFile {
if let contents = self.regularFileContents {
if let image: CPImage = CPImage(data: contents) {
#if os(iOS)
return image.size
#elseif os(OSX)
if let rep = image.representations.first {
return NSMakeSize(CGFloat(rep.pixelsWide),
CGFloat(rep.pixelsHigh))
}
#endif
}
}
}
return nil
}
}
extension NSTextAttachment {
func imageSize() -> CPSize? {
var imageSize: CPSize?
if self.fileType != nil &&
AttachmentFileType(rawValue: self.fileType!) != nil {
if self.bounds.size.width > 0 {
imageSize = self.bounds.size
} else if self.image?.size != nil {
imageSize = self.image!.size
} else if let fileWrapper = self.fileWrapper {
if let imageSizeFromFileWrapper = fileWrapper.imageSize() {
imageSize = imageSizeFromFileWrapper
}
}
}
return imageSize
}
}
#if os(iOS)
import UIKit
public typealias CPSize = CGSize
#elseif os(OSX)
import Cocoa
public typealias CPSize = NSSize
#endif
#if os(iOS)
import UIKit
public typealias CPImage = UIImage
#elseif os(OSX)
import AppKit
public typealias CPImage = NSImage
#endif
enum AttachmentFileType: String {
case jpeg = "public.jpeg"
case jpg = "public.jpg"
case png = "public.png"
case gif = "public.gif"
}