private static string DetectTappedUrl(UIGestureRecognizer tap, UILabel control) { CGRect bounds = control.Bounds; NSAttributedString attributedText = control.AttributedText; // Setup containers using var textContainer = new NSTextContainer(bounds.Size) { LineFragmentPadding = 0, LineBreakMode = control.LineBreakMode, MaximumNumberOfLines = (nuint)control.Lines }; using var layoutManager = new NSLayoutManager(); layoutManager.AddTextContainer(textContainer); using var textStorage = new NSTextStorage(); textStorage.SetString(attributedText); using var fontAttributeName = new NSString("NSFont"); var textRange = new NSRange(0, control.AttributedText.Length); textStorage.AddAttribute(fontAttributeName, control.Font, textRange); textStorage.AddLayoutManager(layoutManager); CGRect textBoundingBox = layoutManager.GetUsedRectForTextContainer(textContainer);
void ResetAttributes(NSColor foregroundColorOverride = null) { // clear user attributes TextStorage.SetAttributes(new NSDictionary(), new NSRange(0, TextStorage.Length)); var r = new NSRange(0, Text.Length); TextStorage.SetString(new NSAttributedString(Text)); TextStorage.SetAlignment(TextAlignment.ToNSTextAlignment(), r); if (Font != null) { // set a global font TextStorage.AddAttribute(NSStringAttributeKey.Font, Font, r); } // paragraph style TextContainer.LineBreakMode = TextTrimming == TextTrimming.WordElipsis ? NSLineBreakMode.TruncatingTail : NSLineBreakMode.ByWordWrapping; var pstyle = NSParagraphStyle.DefaultParagraphStyle.MutableCopy() as NSMutableParagraphStyle; pstyle.Alignment = TextAlignment.ToNSTextAlignment(); if (TextTrimming == TextTrimming.WordElipsis) { pstyle.LineBreakMode = NSLineBreakMode.TruncatingTail; } TextStorage.AddAttribute(NSStringAttributeKey.ParagraphStyle, pstyle, r); // set foreground color override if (foregroundColorOverride != null) { TextStorage.AddAttribute(NSStringAttributeKey.ForegroundColor, foregroundColorOverride, r); } // restore user attributes foreach (var att in Attributes) { AddAttributeInternal(att); } }