Hello everyone, I am having an issue where the attributed text that I have in my UITextView is not scaling dynamically with phone text size, whenever I remove the attributed text logic, it scales fine, however, with it, it stays at a set font size.
struct AutoDetectedClickableDataView: UIViewRepresentable {
let text: String
@Binding var height: CGFloat
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.dataDetectorTypes = [.phoneNumber, .address, .link]
textView.isEditable = false
textView.isScrollEnabled = false
textView.backgroundColor = .clear
textView.font = UIFont.preferredFont(forTextStyle: .body) /*UIFontMetrics(forTextStyle: .body).scaledFont(for: UIFont.systemFont(ofSize: 16.0)) */
textView.adjustsFontForContentSizeCategory = true
textView.textContainer.lineBreakMode = .byWordWrapping
textView.textContainerInset = .zero
textView.textContainer.lineFragmentPadding = 0
textView.translatesAutoresizingMaskIntoConstraints = false
textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
textView.setContentHuggingPriority(.defaultHigh, for: .horizontal)
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
let attributed = NSMutableAttributedString(string: text, attributes: [
.font: UIFont.preferredFont(forTextStyle: .body)
])
let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.address.rawValue |
NSTextCheckingResult.CheckingType.link.rawValue |
NSTextCheckingResult.CheckingType.phoneNumber.rawValue)
detector?.enumerateMatches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count)) { match, _, _ in
guard let match = match else { return }
attributed.addAttributes([
.foregroundColor: UIColor.systemBlue,
.underlineStyle: NSUnderlineStyle.single.rawValue,
], range: match.range)
}
uiView.attributedText = attributed
// uiView.text = text
DispatchQueue.main.async {
uiView.layoutIfNeeded()
let fittingSize = CGSize(width: uiView.bounds.width, height: .greatestFiniteMagnitude)
let size = uiView.sizeThatFits(fittingSize)
height = size.height
}
}
}