1
0
mirror of https://github.com/metabolist/metatext synced 2024-12-29 03:01:07 +01:00
metatext-app-ios-iphone-ipad/Extensions/NSMutableAttributedString+Extensions.swift

57 lines
2.0 KiB
Swift
Raw Normal View History

2020-08-08 11:10:05 +02:00
// Copyright © 2020 Metabolist. All rights reserved.
2020-08-31 01:33:11 +02:00
import Mastodon
import SDWebImage
2020-09-05 04:31:43 +02:00
import UIKit
2021-02-22 08:10:34 +01:00
import ViewModels
2020-08-08 11:10:05 +02:00
extension NSMutableAttributedString {
2021-02-22 08:10:34 +01:00
func insert(emojis: [Emoji], view: UIView & EmojiInsertable, identityContext: IdentityContext) {
2021-01-12 08:33:35 +01:00
for emoji in emojis {
2020-08-08 11:10:05 +02:00
let token = ":\(emoji.shortcode):"
while let tokenRange = string.range(of: token) {
2021-02-22 08:10:34 +01:00
let attachment = AnimatedTextAttachment()
2021-02-27 21:27:49 +01:00
let imageURL: URL?
2021-02-22 08:10:34 +01:00
2021-03-06 03:25:18 +01:00
if identityContext.appPreferences.animateCustomEmojis,
2021-02-27 21:27:49 +01:00
let urlString = emoji.url {
2021-02-27 22:29:30 +01:00
imageURL = URL(stringEscapingPath: urlString)
2021-02-27 21:27:49 +01:00
} else if let staticURLString = emoji.staticUrl {
2021-02-27 22:29:30 +01:00
imageURL = URL(stringEscapingPath: staticURLString)
2021-02-22 08:10:34 +01:00
} else {
2021-02-27 21:27:49 +01:00
imageURL = nil
}
attachment.imageView.sd_setImage(with: imageURL) { image, _, _, _ in
attachment.image = image
DispatchQueue.main.async {
view.setNeedsDisplay()
}
2021-02-22 08:10:34 +01:00
}
2020-08-08 11:10:05 +02:00
2021-02-02 23:38:04 +01:00
attachment.accessibilityLabel = emoji.shortcode
2020-08-27 07:10:31 +02:00
replaceCharacters(in: NSRange(tokenRange, in: string), with: NSAttributedString(attachment: attachment))
2020-08-08 11:10:05 +02:00
}
}
}
func resizeAttachments(toLineHeight lineHeight: CGFloat) {
enumerateAttribute(.attachment, in: NSRange(location: 0, length: length), options: []) { attribute, _, _ in
guard let attachment = attribute as? NSTextAttachment else { return }
attachment.bounds = CGRect(x: 0, y: lineHeight * -0.25, width: lineHeight, height: lineHeight)
}
}
2021-02-02 19:02:30 +01:00
func appendWithSeparator(_ string: NSAttributedString) {
append(.init(string: .separator))
append(string)
}
func appendWithSeparator(_ string: String) {
appendWithSeparator(.init(string: string))
}
2020-08-08 11:10:05 +02:00
}