psharanda / atributika Goto Github PK
View Code? Open in Web Editor NEWConvert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.
License: MIT License
Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.
License: MIT License
Hi,
After archive my project, i got this error when try submit to apple thought Xcode:
2018-07-27 22:10:40 +0000 [OPTIONAL] Didn't find archived user entitlements for <DVTFilePath:0x7fa4ed4b7020:'/Users/paulo/Library/Developer/Xcode/Archives/2018-07-27/xxx 27-07-18 19.10.xcarchive/Products/Applications/XXX.app/Frameworks/Atributika.framework'>:
Error Domain=NSCocoaErrorDomain Code=4 "Item at "/Users/paulo/Library/Developer/Xcode/Archives/2018-07-27/xxx 27-07-18 19.10.xcarchive/Products/Applications/XXX.app/Frameworks/Atributika.framework" did not contain a "archived-expanded-entitlements.xcent" resource."
UserInfo={NSLocalizedDescription=Item at "/Users/paulo/Library/Developer/Xcode/Archives/2018-07-27/xxx 27-07-18 19.10.xcarchive/Products/Applications/XXX.app/Frameworks/Atributika.framework" did not contain a "archived-expanded-entitlements.xcent" resource.}
I've got the following text:
<p>Je ontvangt je factuur elke maand per post. Daarvoor betaal je € 2,54 per maand. <br />Wil je deze kosten besparen? Meld je dan aan voor een gratis digitale factuur. <a href=\"https://www.google.nl/my/instellingen#betaalgegevens\">Pas je instellingen aan ></a></p>
In the code I've added:
let a = Style("a").foregroundColor(.customRed()).underlineStyle(.styleSingle)
let all = Style.font(.defaultMediumFont(withSize: 12.0)).foregroundColor(.invoiceRemarksGray()).kern(-0.3)
self.remarksDescriptionLabel.attributedText = decoded.style(tags: a)
.styleAll(all)
.stylePhoneNumbers(Style.foregroundColor(.customRed()))
.styleLinks(Style.foregroundColor(.customRed()))
self.remarksDescriptionLabel.onClick = { label, detection in
switch detection.type {
...
}
But I never get a onClick event!?
In Swift 4 NSFontAttributeName is replaced with NSAttributedStringKey.font. I suspect that's the issue.
It work wrong with Bold/Italic nested tags, example :
<br><u><i><b>Italicunderline</b></i></u>
. How can I show this html?
Hello,
I would like to try the library in my project.
Unfortunately CocoaPods shows an error on installation process:
$ pod install
Analyzing dependencies
[!] Unable to find a specification for `Atributika`
My Podfile:
target 'Project'
use_frameworks!
pod 'Atributika'
Is any way to install the Atributika via CocoaPods?
Thanks
Great component. Are there any plans for Swift 4.2 support? As of now, it does not compile.
Is it possible to set AttributedLabel LineSpacing?
Hi,
would it be possible to honour basic HTML styling attributes? We have a basic HTML text like this:
Monday - Friday: <font color="#6cc299"> 8:00 - 19:00</font>
and the tags get transformed / stripped off, but the color attribute is lost. Or is there a way how to achieve this with a TagTransformer anyhow? Please note that the color attribute varies in the HTML text, so applying one style to FONT tag is not the way to go.
Thanks
Similarly to #27, I'm having compilation errors when archiving with Xcode Version 9.3.1 (9E501).
Undefined symbols for architecture arm64:
"protocol witness table for __C.NSAttributedStringKey : Swift.Equatable in Foundation", referenced from:
function signature specialization <Arg[0] = Owned To Guaranteed, Arg[1] = Dead> of generic specialization <__C.NSAttributedStringKey, Any> of static (extension in Swift):Swift._NativeDictionaryBuffer< where A: Swift.Hashable>.fromArray([(A, B)]) -> Swift._NativeDictionaryBuffer<A, B> in MutableAttributedString+Utils.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Instead of mentioning Hashable, like in #27, my error mentions Equatable.
I was able to fix this by adding:
#if swift(>=4.1)
extension NSAttributedStringKey: Equatable { }
#endif
Would you consider adding this workaround while we wait for the inner Swift bug to be fixed?
Thanks!
@psharanda In the latest release, there is a class AtributedLabel which provides onClick events. I want such feature for a UITextView. Is that possible with version 3.1.4?
I'm trying to use italic but does Atributika not support < em > and < i > tags?
When trying to compile I got an Xcode error "Command failed due to signal: Segmentation fault: 11" when trying to use .style on a String.
Hi , Style.Swift line 84 and AttributedText.swift line 99 crash , swift 4.1 , Xcode 9 latest version , ios 11 ,
just copy pasted your "link" and "all" code and crashesh without doing anything else
here's the code : `let tweetLabel = AttributedLabel()
let all = Style.font(.systemFont(ofSize: 20))
let link = Style
.foregroundColor(.blue, .normal)
tweetLabel.attributedText = "@Hey"
.styleHashtags(link)
.styleMentions(link)
.styleLinks(link)
.styleAll(all)`
adding .foregroundColor(.brown, .highlighted)
to link will result. style.swift to crash o.w AttributeText.swift does
I have integrated this in tableview cells with automatic layout. Text is displayed properly, however button frame for touch detection appears to be incorrect. PFA the log and the xcode view debugger image. You can check 3 butons frame's. Frame for the 5 points is completely off the track.
Hi,
First of all, I am really impressed by this project and appreciate the efforts you put in.
Just want to know, if it possible to support bullet points and numbered list?
I am happy to create a PR if you guide me on how to's and basic project structure.
Hi,
href are not working. The following code snippet is an example. Can you look into it where we did the mistake?
Also, unable to click Facebook link. If I am displaying as Facebook.com, it is clickable.
let href = "<a href=\"https://www.google.com/\">Google.com</a> href <a href=\"https://www.facebook.com/\">Facebook</a>"
let a = Style("a").foregroundColor(.green).underlineStyle(.styleSingle)
let all = Style.font(.systemFont(ofSize: 20.0)).foregroundColor(.gray)
let link = Style.foregroundColor(.green, .normal).foregroundColor(.red, .highlighted)
hrefLink.attributedText = href.style(tags: a)
.styleAll(all)
.styleLinks(link)
hrefLink.numberOfLines = 0
hrefLink.onClick = { label, detection in
switch detection.type {
case .tag(let tag):
let t = tag.attributes
if let href = t["href"] {
if let url = URL(string: href) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:]
, completionHandler: nil)
} else {
// Fallback on earlier versions
}
}
}
case .link(let url):
UIApplication.shared.open(url, options: [:]
, completionHandler: nil)
default:
break
}
}
Text with & characters will strip all styled text following said character. See the following example:
let msg = "Hello & <b>Welcome!</b>"
let b = Style("b").font(Font(name: "Verdana-Bold", size: 22)!)
let strCopy = msg.style(tags: [b]).styleAll(Style.font(Font(name: "Verdana", size: 22)!))
txtView.attributedText = strCopy.attributedString
Displayed text in txtView will simply be: "Hello "
I understand Atributika supports HTML characters so perhaps that is what is causing it? Is it possible to work around that or disable it somehow?
Hi,
My
tags was not replaced:
My code:
let paragraph = NSMutableParagraphStyle()
paragraph.lineBreakMode = .byTruncatingTail
let all = Style.font(.systemFont(ofSize: 14)).foregroundColor(.white).paragraphStyle(paragraph)
lbSynopsis.attributedText = product.synopsis.styleAll(all).attributedString
Can anyone help me?
when i set numberOfLine = 1 it get sizeToFit() but when i try to multiline then AttributedLabel did not set width based on text. Its become full width
The images in html text do not show at all. How is it possible to implement images while using atributika.
Thanks
When using Carthage [static frameworks], the linker fails. Unchecking Gather Coverage Data
in Atributika's test scheme fixes this issue.
Hello Pavel Sharanda,
I'm pleased with this library and intended to use with one of my projects, I would say it's very robust and great in term of performance but there is an issue when a & comes within tag.
Below is the HTML for your reference.
<p><a data-mention=\\\"0F9o0000000PBpMCAW\\\" href=\\\"https://www.google.com\\\”>@Physic & Chemistry</a>\\U00a0<a data-mention=\\\"0F9o000000094o4CAA\\\" href=\\\"https://www.google.com\\\”>@College Success</a>\\U00a0sorry for the short notice, but a great seminar to share with all of you .</p>
I received only Physic as the result nsattributedstring.
A quick reply would be appreciated.
Thanks.
It works great for all tags of HTML. But using 'a' tag a href = "url" is a major scope. If we could get a support for that, it will be great. Thanks
Is it possible to have full HTML support in this ? I have a label in which I had set attributedText with NSAttributedString which consorting all data with html tags.I need Hash tag detection implementation in that.
Example of trouble string:
Hello <a class="big" target="" href="http://foo.com">world</a>!
When I click at link framework returns only one attribute entry in tag dictionary
["class":"big"]
Any idea how I could render ordered lists <ol>
with Atributika?
@psharanda If I use the style methods to highlight then Unicode is replaced with an empty string. Basically, I want to give support for Emojis. Is there not support for Unicode chars or I am missing out something?
Hi !
I have this when i'm trying to build :
Type 'NSAttributedStringKey' (aka 'NSString') has no member 'font'
and so on .. :( any help pls ?
Hi, I'm using Atributika a while and it's very great, but when I update to xcode 9 there's some error popped up.
Totally 23 issues i'll post some of them below:
Cannot convert value of type '[NSAttributedStringKey : Any]' (aka 'Dictionary<NSString, Any>') to expected argument type '[String : Any]?'
Type 'NSAttributedStringKey' (aka 'NSString') has no member 'font'
Type 'NSAttributedStringKey' (aka 'NSString') has no member 'foregroundColor'
Hope you can get it fixed soon.
Thanks
Highlighting is missing for few letters of the tagged link. Here is the example text(I am tagging a hashtag with a link)
Worried about delivery? You must know these things!
\r\nLINK
\n <a style="text-decoration:none" href="LINK"><font color="#2b5998">#<font color="#2b5998">Childbirth <a style="text-decoration:none" href="LINK"><font color="#2b5998">#<font color="#2b5998">Expectingababy
If I remove all the \r tags from HTML then it works fine
< href="https://www.w3schools.com">This is link I have set this link to 'AttributedLabel' but it not working. when i click on "This is link" it went to case .tag(let tag): and get tag "Tag(name: "a", attributes: [:])". why i am not getting attributes? i have remove <a?> in href for here just to display proper link in issue
@psharanda Is there any way I can convert the NSAttributedString that I received using this library back again to HTML String?
The title says it all.
I need help. I cannot display image between text using NSTextAttachment.
Here is my code:
let image1Attachment = NSTextAttachment()
image1Attachment.image = UIImage(named: "profile")
let all = Style.font(UIFont.systemFont(ofSize: 17)).foregroundColor(.black)
let atch = Style("attachment").attachment(image1Attachment)
attributed.attributedText = "Hello this is my attachment <attachment></attachment> A simple image"
.style(tags: [all, atch])
.styleAll(all)
Thanks for such a nice library!
Is there any way to remove / replace html entities like '«'; / '»'; , '—'; , and many-many others? Hope there's some easy way to do this and i won't have to replace each entity by myself :)
I was using "html2String" String extension mentioned here early for this
Hi,
I'ld like to use this great module.
Please give me a example working in TableViewCell.
I tried this, but it can't work correctly. it is not tappable.
Thanks.
Here is my sample code. The <code>
tag displays well in red color. But the <strike>
tag does not show a strikethrough. What seems to be wrong with my code?
let all = Style.font(.systemFont(ofSize: 20))
let strike = Style("strike").strikethroughStyle(.styleSingle).strikethroughColor(.black)
let code = Style("code").foregroundColor(.red)
label5.attributedText = "<code>my code</code> <strike>test</strike> testing"
.style(tags: [strike,code])
.styleAll(all)
Is it possible to make href links clickable? I would like to be able to get the 'onClick' event on the AttributedLabel or the link detection on UITextView for this case:
"Hey\r\n<a style=\"text-decoration:none\" href=\"http://www.google.com\">Hello\r\nWorld</a>s"
I currently only managed to get the 'onClick' event for plain links, e.g "Hey http://www.google.com Hello Worlds"
Hey! I'm trying to figure out how to convert <a>
Tags into clickable links. I tried .style(links:)
but that wouldn't work. Do I miss something very obvious?
Hello, before all thank you very much for this library. I would like to ask you if it is possible to add case insensitive tags recognition. For example:
Style("sup")
should match both tags below:
<sup>Superscript</sup>
<SUP>Superscript</SUP>
However only the lowercased tag is matched. At the moment, to overcome this I have to either duplicate the Style for an uppercase condition, or do a string replace.
Hi,
I have a text which might include "&" character, for example "Travel & Talk". I would like to format this text and show all the formatted text as an attributed string, but only "Travel" is shown in the result attributed string, rest of the string is removed.
I guess the reason is this line in the String+Detection.swift file:
if let textString = scanner.scanUpToCharacters(from: CharacterSet(charactersIn: "<&")) {
...
Example Code:
let aStyle = Style("a")
.underlineStyle(.styleSingle)
let html = "Travel & Talk"
let attributedText = html
.style(tags: aStyle)
print(attributedText)
Result:
AttributedText(string: "Travel ", detections: [], baseStyle: Atributika.Style(name: "", typedAttributes: [:]))
Is there any way that we can also include "&" character in the attributed string?
Starting text with a tag applies that tag throughout, even though there is a matching end tag.
"Save $1.00 on any order!" comes out all bold.
"Save $1.00 on any order!" correctly bolds only the two sections.
With this call:
let desc = Atributika(text: text,
styles: [
"b" : [.font( UIFont.boldSystemFont(ofSize: 14))]
],
baseStyle: [
.font( UIFont.systemFont(ofSize: 14)), .foregroundColor(UIColor.red)
])
.buildAttributedString()
Great library, it's very useful to style links and tags.
It would be nice to have custom truncation tokens similar to TTAttributedLabel to replace the default ellipses in UILabel so I can stop using TTAttributedLabel in certain cases.
It'd be similar to
https://github.com/TTTAttributedLabel/TTTAttributedLabel/blob/b0f1f93d5d4368a7aaf52e848013a1b40b00dc3c/README.md
This is a really nice framework, but I can't seem to get the foreground colour working. I've dropped the first Hello World example directly into my project, but it all shows up black. I'm not sure if I'm missing something.
Hi!
Thanks for this awesome library! One of the most powerful out there.
I have a question:
Is it possible to get the frame of a specific text using NSRange?
I want to get the frame so that I can add a subview in that coordinate, like a custom button or a view.
For example the text this is a text and this is a button
How can I get the frame of the button
word so that I can add a subview in that coordinate that will cover that word.
Any help is greatly appreciated.
Thanks a lot!
Hello!
This library is very excellent.
I am using NSMutableAttributedString to add NSTextAttachment based on the example you gave in https://github.com/psharanda/Atributika/issues/33
It was working well, however when I added onClick
on my Attributed label, it cannot detect tag attributes. I think this is because the NSMutableAttributedString doesn't have the detections from the AttributedText.
I have the following code:
It inserts a custom emoji.
I wanted to detect a tag with class mentioned-user
This is a mentioned user but I don't want to use the built-in mentions detection because I want to get the user id from the tag.
plainView.message
is the AttributedLabel
Any help is very much appriciated.
//this is the Style I used for my custom mention tag
let span = Style("mentioned").foregroundColor(UIColor.CustomColor.cryptoYellow, .normal)
.foregroundColor(.blue, .highlighted)
let str = messageTxt.style(tags: tags, transformers: transformers)
let mutableAttrStr = NSMutableAttributedString(attributedString: str.attributedString)
var locationShift = 0
for detection in str.detections {
switch detection.type {
case .tag(let tag):
if let emojiColon = tag.attributes["colon"] {
let textAttachment = NSTextAttachment()
let custom = CustomEmoji.customEmojis[emojiColon]!
if custom.ext == "gif" {
if let data = custom.data {
let image = UIImage.gif(data: data)
textAttachment.image = image
} else {
Alamofire.request(custom.imageUrl).responseImage { (response) in
if let image = response.result.value {
let image = UIImage.gif(data: response.data!)
DispatchQueue.main.async {
textAttachment.image = image
}
}
}
}
} else {
textAttachment.image = custom.image
}
textAttachment.setImageHeight(20)
let imageAttrStr = NSAttributedString(attachment: textAttachment)
let nsrange = NSRange.init(detection.range, in: mutableAttrStr.string)
mutableAttrStr.insert(imageAttrStr, at: nsrange.location + locationShift)
locationShift += 1
}
default:
break
}
}
plainView.message.attributedText = mutableAttrStr
.styleLinks(link)
.styleAll(all)
plainView.message.onClick = { label, detection in
switch detection.type {
case .tag(let tag):
let t = tag.attributes
if let spanClass = t["class"] {
if spanClass == "mentioned-user" {
let id = t["data-userid"] ?? ""
let user_name = t["data-uname"] ?? ""
self.selectDelegate?.selectedUserId(id)
}
} else if let href = t["href"] {
if let url = URL(string: href) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
} else if let type = t["type"] {
if type == "channel" {
if let id = t["id"] {
self.selectDelegate?.selectedConvo(id)
}
}
}
default:
break
}
}
Just pod install'd 4.4.0 and am getting the following:
Undefined symbols for architecture arm64:
"protocol witness table for __C.NSAttributedStringKey : Swift.Hashable in Foundation", referenced from:
function signature specialization <Arg[0] = Owned To Guaranteed, Arg[1] = Dead> of generic specialization <preserving fragile attribute, Atributika.StyleType, [__C.NSAttributedStringKey : Any]> of static (extension in Swift):Swift._NativeDictionaryBuffer< where A: Swift.Hashable>.fromArray([(A, B)]) -> Swift._NativeDictionaryBuffer<A, B> in RegulationDetailController.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I'm not sure this is actually Atributika's problem yet but it's in the error so I thought I"d put it here while I try to track down what is going on. Anyone else see this?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.