Skip to content

Commit cc821bf

Browse files
committed
NSTextAttachment with image example
1 parent 75cf5ea commit cc821bf

File tree

4 files changed

+56
-1
lines changed

4 files changed

+56
-1
lines changed

Demo/Assets.xcassets/Contents.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"info" : {
3+
"version" : 1,
4+
"author" : "xcode"
5+
}
6+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"images" : [
3+
{
4+
"idiom" : "universal",
5+
"scale" : "1x"
6+
},
7+
{
8+
"idiom" : "universal",
9+
"filename" : "icons8-scissors-26.png",
10+
"scale" : "2x"
11+
},
12+
{
13+
"idiom" : "universal",
14+
"scale" : "3x"
15+
}
16+
],
17+
"info" : {
18+
"version" : 1,
19+
"author" : "xcode"
20+
}
21+
}
Loading

Demo/Snippet.swift

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,33 @@ func stringWithBoldItalicUnderline() -> NSAttributedString {
146146
return str
147147
}
148148

149+
func stringWithImage() -> NSAttributedString {
150+
151+
let str = "Running with <img id=\"scissors\"></img>!".style(tags: [])
152+
153+
let mutableAttrStr = NSMutableAttributedString(attributedString: str.attributedString)
154+
155+
var locationShift = 0
156+
for detection in str.detections {
157+
switch detection.type {
158+
case .tag(let tag):
159+
if let imageId = tag.attributes["id"] {
160+
let textAttachment = NSTextAttachment()
161+
textAttachment.image = UIImage(named: imageId)
162+
let imageAttrStr = NSAttributedString(attachment: textAttachment)
163+
let nsrange = NSRange.init(detection.range, in: mutableAttrStr.string)
164+
mutableAttrStr.insert(imageAttrStr, at: nsrange.location + locationShift)
165+
locationShift += 1
166+
}
167+
default:
168+
break
169+
}
170+
}
171+
172+
173+
return mutableAttrStr
174+
}
175+
149176
func allSnippets() -> [NSAttributedString] {
150177
return [
151178
stringWithAtributikaLogo(),
@@ -160,7 +187,8 @@ func allSnippets() -> [NSAttributedString] {
160187
stringWithTagAndHashtag(),
161188
stringWithUnorderedList(),
162189
stringWithHref(),
163-
stringWithBoldItalicUnderline()
190+
stringWithBoldItalicUnderline(),
191+
stringWithImage()
164192
]
165193
}
166194

0 commit comments

Comments
 (0)