malcommac / swiftrichstring Goto Github PK
View Code? Open in Web Editor NEWđ©âđš Elegant Attributed String composition in Swift sauce
License: MIT License
đ©âđš Elegant Attributed String composition in Swift sauce
License: MIT License
Add a new func to String
instances which allows you to parse a tagged (html-like) string and return the NSMutableAttributed
string.
It will be called renderTags(withStyles:)
.
Follows an example:
let sourceTaggedString = "<center>The quick brown fox</center>\njumps over the lazy dog is an <italic>English-language</italic> pangramâa phrase that contains <italic>all</italic> of the letters of the alphabet. It is <extreme><underline>commonly</underline></extreme> used for touch-typing practice."
let _ = sourceTaggedString.renderTags(withStyles: [tag_center,tag_italic,tag_extreme,tag_underline])
Build failed with latest version 2.0.5 and XCode 9.4 / iOS 11.4
(deployment target iOS 9.1)
Pods/SwiftRichString/Sources/SwiftRichString/Attributes/CommonsAttributes.swift:57:53: 'SymbolicTraits' is not a member type of 'UIFontDescriptor'
@malcommac
Every time I apply Stroke attribute to text any font-icon, it just disappears. Why?
static let nameTitle = Style({
$0.color = .white
$0.stroke = StrokeAttribute(color: .black, width: 0.1)
$0.font = FontAttribute(font: .pageTitle)
$0.shadow = ShadowAttribute(color: UIColor.black.withAlphaComponent(0.2), radius: 2.0, offset: CGSize(width: 1, height: 1))
})
Hi. I want to implement such thing:
let highlightedStyle = StyleRegEx(base: style, pattern: patternText) {
$0.font = UIFont.systemFont(ofSize: 18, weight: .bold)
$0.color = UIColor.black
}
Currently I cannot get such results
I made styles like this:
let normal = Style { $0.font = UIFont.systemFont(ofSize: 8); $0.color = UIColor.black }
let red = Style { $0.color = UIColor.red }
let group = StyleGroup(base: normal, ["red": red])
"This font size is small, <red>This font size is big</red>".set(style: group)
Is this a preferred effect?
Hi,
I am facing issue in applying multiple styles in textview text. If text contains email regex then it is in different style. If it is contains any numbers than numbers will also display in different style.
So how can I achieve that using this?
How can i set shadow for style?
I believe UITextView.typingAttributes contains the "default" style for UITextView. I'd like to be able to set it with the styles I'm using in the attributed text.
(I'm having an issue with getting a default font to be registered for an empty UITextView that will be edited.)
Hi, your lib is great đ
Do you have a plan to add handle touch feature to tag?
This is related to the following question in SO:
I completely don't know how to create paragraph with offsets from previous part of text. Can you help me with that?
it looks like it doesnt work at all;)
A compile error occurs when compiling with Xcode 9 (beta) using SwiftRichString (0.9.8).
When having swift compiler version set to "Swift 3.2" I get the following error in file Extention.swift line 78:
Cannot express tuple conversion '(Int?, Element?)' to '(index: Int?, item: Style?)'
Hi,
I've just updated from 2.0.1 to 2.0.2, and all my styles are goneâŠ
let baseFontSize: CGFloat = 16
let headerStyle = Style {
$0.font = UIFont.boldSystemFont(ofSize: self.baseFontSize * 1.15)
$0.lineSpacing = 1
$0.kerning = Kerning.adobe(-20)
}
let boldStyle = Style {
$0.font = UIFont.boldSystemFont(ofSize: self.baseFontSize)
}
let italicStyle = Style {
$0.font = UIFont.italicSystemFont(ofSize: self.baseFontSize)
}
let style = StyleGroup(base: Style {
$0.font = UIFont.systemFont(ofSize: self.baseFontSize)
$0.lineSpacing = 2
$0.kerning = Kerning.adobe(-15)
}, [
"h3": headerStyle,
"h4": headerStyle,
"h5": headerStyle,
"strong": boldStyle,
"b": boldStyle,
"em": italicStyle,
"i": italicStyle,
"li": Style {
$0.paragraphSpacingBefore = self.baseFontSize / 2
$0.firstLineHeadIndent = self.baseFontSize
$0.headIndent = self.baseFontSize * 1.71
},
"sup": Style {
$0.font = UIFont.systemFont(ofSize: self.baseFontSize / 1.2)
$0.baselineOffset = Float(self.baseFontSize) / 3.5
}])
attrString = bodyHTML.set(style: style)
Original text is:
<strong>Parler du don d'organe n'est plus tabou. Je me renseigne, j'en discute avec mes proches,... et je décide!</strong>
En Belgique, au dĂ©but des annĂ©es 2000, le nombre de donneurs dâorganes avait tendance Ă diminuer et les listes dâattente Ă augmenter considĂ©rablement ayant comme corollaire une augmentation de la mortalitĂ© des patients inscrits sur les listes dâattente.
Soucieux de cette situation, en juin 2005, le Ministre en charge de la SantĂ© publique a souhaitĂ© mettre sur pied une vaste campagne de sensibilisation entiĂšrement dĂ©diĂ©e au don dâorganes.
Depuis, de nombreuses actions entreprises par le SPF Santé publique viennent renforcer toutes celles qui sont accomplies au quotidien par les coordinateurs de transplantation, les coordinateurs locaux de don, les associations de familles de donneurs, les associations de patients transplantés et ce, depuis de trÚs nombreuses années.
<strong>Objectifs poursuivis</strong>
Les objectifs principaux de cette campagne sont:
<li style="text-align: justify;">âą dâamĂ©liorer la sensibilisation au don auprĂšs des diffĂ©rents groupes auxquels les messages sâadressent,</li>
<li style="text-align: justify;">âą dâinviter les citoyens à «oser» en parler en famille, entre amis, entre collĂšgues. Aborder la mort â sa propre mort â reste relativement tabou pour beaucoup.</li>
<strong>Pour en savoir plus... <a href="http://www.health.belgium.be/fr/sante/prenez-soin-de-vous/debut-et-fin-de-vie/don-dorganes" target="_blank">www.health.belgium.be/fr/sante/prenez-soin-de-vous/debut-et-fin-de-vie/don-dorganes</a></strong>
When I apply tags to a very large text, the attributes start getting applied to strange locations in text. I tried playing with this but haven't yet detected a pattern.
Question: Is there a size limit for the text being tagged?
Remove throws
in MarkupString in favour of nil
results when parsing fails.
It will remove lots of boilerplate code.
Using following code:
let titleStyle = Style("title", {
$0.font = FontAttribute(font: .WorkSansExtraBold(17))
$0.align = .center
$0.color = UIColor.white
$0.stroke = StrokeAttribute(color: UIColor.black, width: 1)
$0.kern = 2
})
And text color becomes transparent. Any ideas why ?
Thanks !
When trying to convert HTML to attributedText with this wonderful tool, the only thing I'm missing is a way to construct the linkURL
with the content of a tag attribute.
I've looked into your code and here's an idea: instead of taking an optional URL for the Style linkURL
property, what about a "URLConvertible
" type?
Here's a draft of what it could look like, but I don't understand your parsing process (yet) to be able to fully implement it.
//MARK: - URLConvertible
/// An enumeration representing the source of the URL to be applied.
///
/// - url: URL type.
/// - string: String url.
/// - tagAttribute: value of attribute from a parsed tag (ie: "href").
/// - tagText: text content from a parsed tag.
public enum URLConvertible {
case url(URL)
case string(String)
case tagAttribute(String)
case tagText
func url(for tag: StyleGroup.TagAttribute?) -> URL? {
switch self {
case .url(let url):
return url
case .string(let string):
return URL(string: string)
case .tagAttribute(let attribute):
return URL(string: tag.attributes[attribute])
case .tagText:
return URL(string: tag.content)
}
}
}
We could then just do the following:
attrString.add(style: StyleGroup(["a" : Style {
$0.linkURL = .tagAttribute("href")
}]))
Hi,
I always had this very simple style with a simple string, and the alignment always worked. Now after upgrading to 2.10 the alignment does not work anymore?
let smaller = Style {
$0.font = Global.Font.RegularFont12
$0.alignment = .center
}
EDIT: I downgraded to 2.0.5, now it works again.
Thanks!
Was this feature removed? I can't seem to find it.
In this great library, it's unclear:
Say I have an attributed string, which has (let's say) ONLY bold and italic sections.
I want to PRODUCE THIS OUTPUT:
This string <b>has</b> only some <i>bold and some</i> italic.
As you know, you can certainly generate html using Apple's built-in generator, but it produces wildly complex CSS output (see below for example).
So, I know that with SwiftRichString you can go FROM something like
This string <b>has</b> only some <i>bold and some</i> italic.
to an NSAttributedString - but can you go in the other direction???
Sorry it's a bit unclear from the doco - or maybe I'm just lame :)
Example of Apple's crappy full-css output...,
if you use .attributedText.data
><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Style-Type" content="text/css">
<title></title>
<meta name="Generator" content="Cocoa HTML Writer">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px 'Open Sans'}
span.s1 {font-family: 'Open Sans'; font-weight: normal; font-style: normal; font-size: 14.00pt}
span.s2 {font-family: 'OpenSans-SemiboldItalic'; font-weight: bold; font-style: italic; font-size: 14.00pt}
</style>
</head>
<body>
<p class="p1"><span class="s1">So, </span><span class="s2">Apple made</span><span class="s1"> this stuff OK</span></p>
</body>
</html>
<
You always have to set lineSpacing
and other paragraph styles after setting some other substring styles.
Hi, Good day. Is there any update for iOS 12 version?
**Xcode version: 10.0
**Swift version: 4.2
I don't have idea how solve it :(
I use
Xcode 10
Swift 4.2
Pod : pod 'SwiftRichString', :git=> 'https://github.com/mezhevikin/SwiftRichString', :branch => 'swift4.2', :inhibit_warnings => true
I have tried use the normal pod from cocoapods but I got the same issue
Can you provide feature of dynamic text size , with font , which introduced in iOS 11
https://developer.apple.com/videos/play/wwdc2017/245/
Is there anyway to cause this library to have the text align default to .right? This would be very helpful for Hebrew and Arabic.
Thanks
I'm converting to version 2 of this library and I just wanted to make sure you removed MarkupString ? What's the recommend upgrade path in that case?
Feature request for URL/link rendering similar to <a>
in HTML
I'm trying to init using the following code:
let bold = Style("bold", {
$0.font = .bold(size: 16)
$0.color = .black
})
Using Xcode 10/Swift 4.2 I get the following error:
Type of expression is ambiguous without more context
Hello, Thank you for this cool framework!. I just need to display an HTML code using this. But when I run the app, my label shows nothing!.
here is my code:
let file = Bundle.main.path(forResource: "html", ofType: "txt")!
do {
htmlBody = try String(contentsOfFile: file, encoding: .utf8)
} catch let error {
print(error)
}
label.attributedText = htmlBody.set(style: "str")
my txt file has all tags and styles so I don't need it to create style group.
How can I fix this?
I have discovered a crash scenario in the following situation:
I have created a simple macOS project that reliably reproduces the issue:
https://github.com/scottcarter/SwiftRichString_MallocBug
I found that if any of the first three criteria is changed, the problem goes away. I.e. if a Debug configuration is used, if the project is compiled with Swift 4.0, or I compile SwiftRichString with Swift 3.2 (using SwiftRichString version 0.9.10).
Could I use this library for set attributes in the not main thread ?
Is there a way to automatically continue the current style when concatenating/appending strings to attributed strings? I'm using set with each string now, but I'm about to move into multiple styles.
Alternatively, a way to set a style based on the style of the final character of an attributed string could also work.
I have this style:
let inputStyle = Style {
$0.font = UIFont.bsFont(type: .medium, size: 13)
$0.color = UIColor.white
$0.kerning = Kerning.point(0.2)
}
On V2.0.1 inputStyle.attributes
returns 3 atrributes.
On V2.0.5 inputStyle.attributes
returns 1 atrributes.
After upgrading Xcode to version 9.3 I can't longer build the project.
<unknown>:0: error: fatal error encountered while reading from module 'SwiftRichString'; please file a bug report with your project and the crash log
<unknown>:0: note: compiling as Swift 3.3, with 'SwiftRichString' built as Swift 4.1 (this is supported but may expose additional compiler issues)
Cross-reference to module 'Foundation'
... NSAttributedStringKey
0 swift 0x0000000107da8ffa PrintStackTraceSignalHandler(void*) + 42
1 swift 0x0000000107da83b6 SignalHandler(int) + 966
2 libsystem_platform.dylib 0x00007fff5e65ff5a _sigtramp + 26
3 libsystem_platform.dylib 000000000000000000 _sigtramp + 2711224512
4 libsystem_c.dylib 0x00007fff5e48a312 abort + 127
5 swift 0x00000001054d6bae swift::ModuleFile::fatal(llvm::Error) + 2062
6 swift 0x00000001054e8f9a swift::ModuleFile::getTypeChecked(llvm::PointerEmbeddedInt<unsigned int, 31>) + 13418
7 swift 0x00000001054f7e17 swift::SILDeserializer::readSILFunction(llvm::PointerEmbeddedInt<unsigned int, 31>, swift::SILFunction*, llvm::StringRef, bool, bool) + 455
8 swift 0x000000010550b00c swift::SILDeserializer::getFuncForReference(llvm::StringRef) + 748
9 swift 0x000000010550c4cd swift::SILDeserializer::readVTable(llvm::PointerEmbeddedInt<unsigned int, 31>) + 605
10 swift 0x000000010520076b swift::SILLinkerVisitor::processClassDecl(swift::ClassDecl const*) + 91
11 swift 0x00000001052473c5 swift::SILModule::lookUpVTable(swift::ClassDecl const*) + 261
12 swift 0x000000010520038f swift::SILLinkerVisitor::linkInVTable(swift::ClassDecl*) + 31
13 swift 0x00000001051ffe45 swift::SILLinkerVisitor::process() + 517
14 swift 0x00000001051ffb6f swift::SILLinkerVisitor::processFunction(swift::SILFunction*) + 79
15 swift 0x0000000105246555 swift::SILModule::linkFunction(swift::SILFunction*, swift::SILOptions::LinkingMode) + 117
16 swift 0x0000000104f843c9 runOnFunctionRecursively(swift::SILFunction*, swift::FullApplySite, swift::SILOptions::LinkingMode, llvm::DenseSet<swift::SILFunction*, llvm::DenseMapInfo<swift::SILFunction*> >&, llvm::ImmutableSet<swift::SILFunction*, llvm::ImutContainerInfo<swift::SILFunction*> >::Factory&, llvm::ImmutableSet<swift::SILFunction*, llvm::ImutContainerInfo<swift::SILFunction*> >, swift::ClassHierarchyAnalysis*) + 4249
17 swift 0x0000000104f82e56 (anonymous namespace)::MandatoryInlining::run() + 342
18 swift 0x0000000104f04db9 swift::SILPassManager::runOneIteration() + 10217
19 swift 0x0000000104f081eb swift::runSILDiagnosticPasses(swift::SILModule&) + 2123
20 swift 0x0000000104407697 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&, swift::FrontendObserver*, swift::UnifiedStatsReporter*) + 32167
21 swift 0x00000001043fde64 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 7908
22 swift 0x00000001043b28b5 main + 18917
23 libdyld.dylib 0x00007fff5e3de115 start + 1
24 libdyld.dylib 0x00000000000000a8 start + 2713853844
String.characters were deprecated in swift4.
I believe that support NSTextAttachment image could be a good feature to have on lib
Hi,
It seem stroke
and StrokeAttribute
is missing from 2.0 ?
Thanks
Hi,
I would like to have a p tag instead of /n or br for paragraph delimitation.
And of course to be able to define a base style for a paragraph that could be changed automatically in favor of other styles selected.
There's a way to set style priority and to successful process this tag?
Right know it just ignore it
Some emojist stoped working after update.
this code is the code I have
let messageStyle = Style {
$0.font = UIFont.systemFont(ofSize: 12)
$0.kerning = Kerning.point(0.3)
$0.color = UIColor.bsBase
}
self.messageLabel.attributedText = "đ".set(style: messageStyle)
Any clues what may have caused this?
Hi,
Is it support nested tags? For example:
<red><13>SomeText</13></red>
Thanks!
It would be nice if there was an easy way to apply defaults to the document. For example: define a document as default right-to-left, define a document with a default font (family, size, etc), define a document with a theme (background color, text color, etc).
All in all, a very nice project. I'm enjoying playing with it.
After updating to 2.0.1 <br>
tags no longer get rendered. Is this an intended behaviour?
Since the vast majority of the codebase is similar to all of these platform a compatible version could be a great enhancement.
Hello.
I would like to report/highlight the breaking changes of the latest versions.
With this simple group declaration
typealias MainFont = Font.HelveticaNeue
enum Font {
enum HelveticaNeue: String {
case light = "Light"
case bold = "Bold"
case boldItalic = "BoldItalic"
func with(size: CGFloat) -> UIFont {
return UIFont(name: "HelveticaNeue-\(rawValue)", size: size)!
}
}
}
let normal = Style {
$0.font = MainFont.light.with(size: 16)
}
let bold = normal.byAdding {
$0.font = MainFont.bold.with(size: 16)
}
let bold_italic = normal.byAdding {
$0.font = MainFont.boldItalic.with(size: 15)
}
let stylesDefs = [
"bold": bold,
"bold_italic": bold_italic,
]
let defaultStyles = StyleGroup(base: normal, stylesDefs)
And the following text:
var text = "This search engine is specifically designed to solve <bold>crosswords</bold> or <bold>arrowords puzzles</bold>.\n\nIn order to solve a word, you can either enter its <bold>definition</bold> or its <bold>pattern</bold>.\n\n<bold_italic>For patterns, you can simply press the spacebar for each unknown letter.</bold_italic>"
text.set(style: defaultStyles)
The output with version 2.0.1 is as expected:
With version 2.0.2 I've this:
With version 2.0.3, this:
And the latest 2.0.4 is the worst:
I've tried to use your new declaration style
let normal = Style {
$0.font = SystemFonts.HelveticaNeue_Light.font(size: 16)
}
let bold = Style {
$0.font = SystemFonts.HelveticaNeue_Bold.font(size: 16)
}
let bold_italic = Style {
$0.font = SystemFonts.HelveticaNeue_BoldItalic.font(size: 15)
}
But it does not solve the issue, I keep getting the output of the last screenshot.
So either it's a breaking change or it's a bug, but for now, I will force the use of version 2.0.1 as it is the only one who gives the expected output.
add method will override all existing attributes.
let styleA = Style {
$0.color = UIColor.white
$0.size = 24
}
let styleB = Style {
$0.color = UIColor.white
$0.size = 14
}
let styleC = Style {
$0.color = UIColor.red
}
let a = "hello".set(style: styleA)
let b = "world!".set(style: styleB)
let ab = (a + b).add(style: styleC)
the expected result of ab should keep different font size and append red color. But real result is reset font size and append red color.
p.s. version 2.0.1
Hi,
I was trying to create an attributed string from this:
"<p><b>5 July</b><br>- It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.<br>- of the printing and typesetting industry. Lorem Ipsum has been the industry's </p>".
with the following code:
let style = Style.default {
$0.font = FontAttribute(.HelveticaNeue_Light, size: 16)
$0.color = ColorPalette.turquoiseBlue
}
let parser = MarkupString(source: news.subtitle, styles: [style])!
let attributedText = parser.render()
The result that I am getting is like this:
"...>- It is a long established..."
Dont know if its a bug or I am doing something wrong.
Im getting this error when trying to compile the project using Carthage pointing out to the beta version of Xcode:
*** Building scheme "SwiftRichString" in SwiftRichString.xcworkspace
Build Failed
Task failed with exit code 65:
/usr/bin/xcrun xcodebuild -workspace /Users/jgarcia/Developer/music-mobile-ios-v3/Carthage/Checkouts/SwiftRichString/SwiftRichString.xcworkspace -scheme SwiftRichString -configuration Release -derivedDataPath /Users/jgarcia/Library/Caches/org.carthage.CarthageKit/DerivedData/SwiftRichString/0.9.8 -sdk iphoneos ONLY_ACTIVE_ARCH=NO BITCODE_GENERATION_MODE=bitcode CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES clean build
This usually indicates that project itself failed to compile. Please check the xcodebuild log for more details: /var/folders/5y/6n4_nl4x40qg1z_6n8d_z9xc0000gp/T/carthage-xcodebuild.pNKVla.log
Any suggestion of what should I do.
Thanks.
The file ViewController.swift in the DemoApp folder has the following code in lines 64-66:
// let sourceURL = URL(fileURLWithPath: "...")
// let sourceText = RichString(sourceURL, encoding: .utf8, [bold,italic])!
// let renderedText = sourceText.text
The method RichString() doesn't seem to exist anywhere. Is there a replacement function? Or is it hiding from me?
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.