Replace TTTAttributedLabel with custom LinkLabel

This commit is contained in:
Shadowfacts 2019-02-03 11:39:27 -05:00
parent 55ed2f5d26
commit ef6047fcb1
Signed by untrusted user: shadowfacts
GPG Key ID: 94A5AB95422746E5
7 changed files with 216 additions and 3139 deletions

View File

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
</dict>
</plist>

View File

@ -1,777 +0,0 @@
// TTTAttributedLabel.h
//
// Copyright (c) 2011 Mattt Thompson (http://mattt.me)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <UIKit/UIKit.h>
#import <CoreText/CoreText.h>
//! Project version number for TTTAttributedLabel.
FOUNDATION_EXPORT double TTTAttributedLabelVersionNumber;
//! Project version string for TTTAttributedLabel.
FOUNDATION_EXPORT const unsigned char TTTAttributedLabelVersionString[];
@class TTTAttributedLabelLink;
/**
Vertical alignment for text in a label whose bounds are larger than its text bounds
*/
typedef NS_ENUM(NSInteger, TTTAttributedLabelVerticalAlignment) {
TTTAttributedLabelVerticalAlignmentCenter = 0,
TTTAttributedLabelVerticalAlignmentTop = 1,
TTTAttributedLabelVerticalAlignmentBottom = 2,
};
/**
Determines whether the text to which this attribute applies has a strikeout drawn through itself.
*/
extern NSString * const kTTTStrikeOutAttributeName;
/**
The background fill color. Value must be a `CGColorRef`. Default value is `nil` (no fill).
*/
extern NSString * const kTTTBackgroundFillColorAttributeName;
/**
The padding for the background fill. Value must be a `UIEdgeInsets`. Default value is `UIEdgeInsetsZero` (no padding).
*/
extern NSString * const kTTTBackgroundFillPaddingAttributeName;
/**
The background stroke color. Value must be a `CGColorRef`. Default value is `nil` (no stroke).
*/
extern NSString * const kTTTBackgroundStrokeColorAttributeName;
/**
The background stroke line width. Value must be an `NSNumber`. Default value is `1.0f`.
*/
extern NSString * const kTTTBackgroundLineWidthAttributeName;
/**
The background corner radius. Value must be an `NSNumber`. Default value is `5.0f`.
*/
extern NSString * const kTTTBackgroundCornerRadiusAttributeName;
@protocol TTTAttributedLabelDelegate;
// Override UILabel @property to accept both NSString and NSAttributedString
@protocol TTTAttributedLabel <NSObject>
@property (nonatomic, copy) IBInspectable id text;
@end
IB_DESIGNABLE
/**
`TTTAttributedLabel` is a drop-in replacement for `UILabel` that supports `NSAttributedString`, as well as automatically-detected and manually-added links to URLs, addresses, phone numbers, and dates.
## Differences Between `TTTAttributedLabel` and `UILabel`
For the most part, `TTTAttributedLabel` behaves just like `UILabel`. The following are notable exceptions, in which `TTTAttributedLabel` may act differently:
- `text` - This property now takes an `id` type argument, which can either be a kind of `NSString` or `NSAttributedString` (mutable or immutable in both cases)
- `attributedText` - Do not set this property directly. Instead, pass an `NSAttributedString` to `text`.
- `lineBreakMode` - This property displays only the first line when the value is `UILineBreakModeHeadTruncation`, `UILineBreakModeTailTruncation`, or `UILineBreakModeMiddleTruncation`
- `adjustsFontsizeToFitWidth` - Supported in iOS 5 and greater, this property is effective for any value of `numberOfLines` greater than zero. In iOS 4, setting `numberOfLines` to a value greater than 1 with `adjustsFontSizeToFitWidth` set to `YES` may cause `sizeToFit` to execute indefinitely.
- `baselineAdjustment` - This property has no affect.
- `textAlignment` - This property does not support justified alignment.
- `NSTextAttachment` - This string attribute is not supported.
Any properties affecting text or paragraph styling, such as `firstLineIndent` will only apply when text is set with an `NSString`. If the text is set with an `NSAttributedString`, these properties will not apply.
### NSCoding
`TTTAttributedLabel`, like `UILabel`, conforms to `NSCoding`. However, if the build target is set to less than iOS 6.0, `linkAttributes` and `activeLinkAttributes` will not be encoded or decoded. This is due to an runtime exception thrown when attempting to copy non-object CoreText values in dictionaries.
@warning Any properties changed on the label after setting the text will not be reflected until a subsequent call to `setText:` or `setText:afterInheritingLabelAttributesAndConfiguringWithBlock:`. This is to say, order of operations matters in this case. For example, if the label text color is originally black when the text is set, changing the text color to red will have no effect on the display of the label until the text is set once again.
@bug Setting `attributedText` directly is not recommended, as it may cause a crash when attempting to access any links previously set. Instead, call `setText:`, passing an `NSAttributedString`.
*/
@interface TTTAttributedLabel : UILabel <TTTAttributedLabel, UIGestureRecognizerDelegate>
/**
* The designated initializers are @c initWithFrame: and @c initWithCoder:.
* init will not properly initialize many required properties and other configuration.
*/
- (instancetype) init NS_UNAVAILABLE;
///-----------------------------
/// @name Accessing the Delegate
///-----------------------------
/**
The receiver's delegate.
@discussion A `TTTAttributedLabel` delegate responds to messages sent by tapping on links in the label. You can use the delegate to respond to links referencing a URL, address, phone number, date, or date with a specified time zone and duration.
*/
@property (nonatomic, unsafe_unretained) IBOutlet id <TTTAttributedLabelDelegate> delegate;
///--------------------------------------------
/// @name Detecting, Accessing, & Styling Links
///--------------------------------------------
/**
A bitmask of `NSTextCheckingType` which are used to automatically detect links in the label text.
@warning You must specify `enabledTextCheckingTypes` before setting the `text`, with either `setText:` or `setText:afterInheritingLabelAttributesAndConfiguringWithBlock:`.
*/
@property (nonatomic, assign) NSTextCheckingTypes enabledTextCheckingTypes;
/**
An array of `NSTextCheckingResult` objects for links detected or manually added to the label text.
*/
@property (readonly, nonatomic, strong) NSArray *links;
/**
A dictionary containing the default `NSAttributedString` attributes to be applied to links detected or manually added to the label text. The default link style is blue and underlined.
@warning You must specify `linkAttributes` before setting autodecting or manually-adding links for these attributes to be applied.
*/
@property (nonatomic, strong) NSDictionary *linkAttributes;
/**
A dictionary containing the default `NSAttributedString` attributes to be applied to links when they are in the active state. If `nil` or an empty `NSDictionary`, active links will not be styled. The default active link style is red and underlined.
*/
@property (nonatomic, strong) NSDictionary *activeLinkAttributes;
/**
A dictionary containing the default `NSAttributedString` attributes to be applied to links when they are in the inactive state, which is triggered by a change in `tintColor` in iOS 7 and later. If `nil` or an empty `NSDictionary`, inactive links will not be styled. The default inactive link style is gray and unadorned.
*/
@property (nonatomic, strong) NSDictionary *inactiveLinkAttributes;
/**
The edge inset for the background of a link. The default value is `{0, -1, 0, -1}`.
*/
@property (nonatomic, assign) UIEdgeInsets linkBackgroundEdgeInset;
/**
Indicates if links will be detected within an extended area around the touch
to emulate the link detection behaviour of UIWebView.
Default value is NO. Enabling this may adversely impact performance.
*/
@property (nonatomic, assign) BOOL extendsLinkTouchArea;
///---------------------------------------
/// @name Acccessing Text Style Attributes
///---------------------------------------
/**
The shadow blur radius for the label. A value of 0 indicates no blur, while larger values produce correspondingly larger blurring. This value must not be negative. The default value is 0.
*/
@property (nonatomic, assign) IBInspectable CGFloat shadowRadius;
/**
The shadow blur radius for the label when the label's `highlighted` property is `YES`. A value of 0 indicates no blur, while larger values produce correspondingly larger blurring. This value must not be negative. The default value is 0.
*/
@property (nonatomic, assign) IBInspectable CGFloat highlightedShadowRadius;
/**
The shadow offset for the label when the label's `highlighted` property is `YES`. A size of {0, 0} indicates no offset, with positive values extending down and to the right. The default size is {0, 0}.
*/
@property (nonatomic, assign) IBInspectable CGSize highlightedShadowOffset;
/**
The shadow color for the label when the label's `highlighted` property is `YES`. The default value is `nil` (no shadow color).
*/
@property (nonatomic, strong) IBInspectable UIColor *highlightedShadowColor;
/**
The amount to kern the next character. Default is standard kerning. If this attribute is set to 0.0, no kerning is done at all.
*/
@property (nonatomic, assign) IBInspectable CGFloat kern;
///--------------------------------------------
/// @name Acccessing Paragraph Style Attributes
///--------------------------------------------
/**
The distance, in points, from the leading margin of a frame to the beginning of the
paragraph's first line. This value is always nonnegative, and is 0.0 by default.
This applies to the full text, rather than any specific paragraph metrics.
*/
@property (nonatomic, assign) IBInspectable CGFloat firstLineIndent;
/**
The space in points added between lines within the paragraph. This value is always nonnegative and is 0.0 by default.
*/
@property (nonatomic, assign) IBInspectable CGFloat lineSpacing;
/**
The minimum line height within the paragraph. If the value is 0.0, the minimum line height is set to the line height of the `font`. 0.0 by default.
*/
@property (nonatomic, assign) IBInspectable CGFloat minimumLineHeight;
/**
The maximum line height within the paragraph. If the value is 0.0, the maximum line height is set to the line height of the `font`. 0.0 by default.
*/
@property (nonatomic, assign) IBInspectable CGFloat maximumLineHeight;
/**
The line height multiple. This value is 1.0 by default.
*/
@property (nonatomic, assign) IBInspectable CGFloat lineHeightMultiple;
/**
The distance, in points, from the margin to the text container. This value is `UIEdgeInsetsZero` by default.
sizeThatFits: will have its returned size increased by these margins.
drawTextInRect: will inset all drawn text by these margins.
*/
@property (nonatomic, assign) IBInspectable UIEdgeInsets textInsets;
/**
The vertical text alignment for the label, for when the frame size is greater than the text rect size. The vertical alignment is `TTTAttributedLabelVerticalAlignmentCenter` by default.
*/
@property (nonatomic, assign) TTTAttributedLabelVerticalAlignment verticalAlignment;
///--------------------------------------------
/// @name Accessing Truncation Token Appearance
///--------------------------------------------
/**
The attributed string to apply to the truncation token at the end of a truncated line.
*/
@property (nonatomic, strong) IBInspectable NSAttributedString *attributedTruncationToken;
///--------------------------
/// @name Long press gestures
///--------------------------
/**
* The long-press gesture recognizer used internally by the label.
*/
@property (nonatomic, strong, readonly) UILongPressGestureRecognizer *longPressGestureRecognizer;
///--------------------------------------------
/// @name Calculating Size of Attributed String
///--------------------------------------------
/**
Calculate and return the size that best fits an attributed string, given the specified constraints on size and number of lines.
@param attributedString The attributed string.
@param size The maximum dimensions used to calculate size.
@param numberOfLines The maximum number of lines in the text to draw, if the constraining size cannot accomodate the full attributed string.
@return The size that fits the attributed string within the specified constraints.
*/
+ (CGSize)sizeThatFitsAttributedString:(NSAttributedString *)attributedString
withConstraints:(CGSize)size
limitedToNumberOfLines:(NSUInteger)numberOfLines;
///----------------------------------
/// @name Setting the Text Attributes
///----------------------------------
/**
Sets the text displayed by the label.
@param text An `NSString` or `NSAttributedString` object to be displayed by the label. If the specified text is an `NSString`, the label will display the text like a `UILabel`, inheriting the text styles of the label. If the specified text is an `NSAttributedString`, the label text styles will be overridden by the styles specified in the attributed string.
@discussion This method overrides `UILabel -setText:` to accept both `NSString` and `NSAttributedString` objects. This string is `nil` by default.
*/
- (void)setText:(id)text;
/**
Sets the text displayed by the label, after configuring an attributed string containing the text attributes inherited from the label in a block.
@param text An `NSString` or `NSAttributedString` object to be displayed by the label.
@param block A block object that returns an `NSMutableAttributedString` object and takes a single argument, which is an `NSMutableAttributedString` object with the text from the first parameter, and the text attributes inherited from the label text styles. For example, if you specified the `font` of the label to be `[UIFont boldSystemFontOfSize:14]` and `textColor` to be `[UIColor redColor]`, the `NSAttributedString` argument of the block would be contain the `NSAttributedString` attribute equivalents of those properties. In this block, you can set further attributes on particular ranges.
@discussion This string is `nil` by default.
*/
- (void)setText:(id)text
afterInheritingLabelAttributesAndConfiguringWithBlock:(NSMutableAttributedString *(^)(NSMutableAttributedString *mutableAttributedString))block;
///------------------------------------
/// @name Accessing the Text Attributes
///------------------------------------
/**
A copy of the label's current attributedText. This returns `nil` if an attributed string has never been set on the label.
@warning Do not set this property directly. Instead, set @c text to an @c NSAttributedString.
*/
@property (readwrite, nonatomic, copy) NSAttributedString *attributedText;
///-------------------
/// @name Adding Links
///-------------------
/**
Adds a link. You can customize an individual link's appearance and accessibility value by creating your own @c TTTAttributedLabelLink and passing it to this method. The other methods for adding links will use the label's default attributes.
@warning Modifying the link's attribute dictionaries must be done before calling this method.
@param link A @c TTTAttributedLabelLink object.
*/
- (void)addLink:(TTTAttributedLabelLink *)link;
/**
Adds a link to an @c NSTextCheckingResult.
@param result An @c NSTextCheckingResult representing the link's location and type.
@return The newly added link object.
*/
- (TTTAttributedLabelLink *)addLinkWithTextCheckingResult:(NSTextCheckingResult *)result;
/**
Adds a link to an @c NSTextCheckingResult.
@param result An @c NSTextCheckingResult representing the link's location and type.
@param attributes The attributes to be added to the text in the range of the specified link. If set, the label's @c activeAttributes and @c inactiveAttributes will be applied to the link. If `nil`, no attributes are added to the link.
@return The newly added link object.
*/
- (TTTAttributedLabelLink *)addLinkWithTextCheckingResult:(NSTextCheckingResult *)result
attributes:(NSDictionary *)attributes;
/**
Adds a link to a URL for a specified range in the label text.
@param url The url to be linked to
@param range The range in the label text of the link. The range must not exceed the bounds of the receiver.
@return The newly added link object.
*/
- (TTTAttributedLabelLink *)addLinkToURL:(NSURL *)url
withRange:(NSRange)range;
/**
Adds a link to an address for a specified range in the label text.
@param addressComponents A dictionary of address components for the address to be linked to
@param range The range in the label text of the link. The range must not exceed the bounds of the receiver.
@discussion The address component dictionary keys are described in `NSTextCheckingResult`'s "Keys for Address Components."
@return The newly added link object.
*/
- (TTTAttributedLabelLink *)addLinkToAddress:(NSDictionary *)addressComponents
withRange:(NSRange)range;
/**
Adds a link to a phone number for a specified range in the label text.
@param phoneNumber The phone number to be linked to.
@param range The range in the label text of the link. The range must not exceed the bounds of the receiver.
@return The newly added link object.
*/
- (TTTAttributedLabelLink *)addLinkToPhoneNumber:(NSString *)phoneNumber
withRange:(NSRange)range;
/**
Adds a link to a date for a specified range in the label text.
@param date The date to be linked to.
@param range The range in the label text of the link. The range must not exceed the bounds of the receiver.
@return The newly added link object.
*/
- (TTTAttributedLabelLink *)addLinkToDate:(NSDate *)date
withRange:(NSRange)range;
/**
Adds a link to a date with a particular time zone and duration for a specified range in the label text.
@param date The date to be linked to.
@param timeZone The time zone of the specified date.
@param duration The duration, in seconds from the specified date.
@param range The range in the label text of the link. The range must not exceed the bounds of the receiver.
@return The newly added link object.
*/
- (TTTAttributedLabelLink *)addLinkToDate:(NSDate *)date
timeZone:(NSTimeZone *)timeZone
duration:(NSTimeInterval)duration
withRange:(NSRange)range;
/**
Adds a link to transit information for a specified range in the label text.
@param components A dictionary containing the transit components. The currently supported keys are `NSTextCheckingAirlineKey` and `NSTextCheckingFlightKey`.
@param range The range in the label text of the link. The range must not exceed the bounds of the receiver.
@return The newly added link object.
*/
- (TTTAttributedLabelLink *)addLinkToTransitInformation:(NSDictionary *)components
withRange:(NSRange)range;
/**
Returns whether an @c NSTextCheckingResult is found at the give point.
@discussion This can be used together with @c UITapGestureRecognizer to tap interactions with overlapping views.
@param point The point inside the label.
*/
- (BOOL)containslinkAtPoint:(CGPoint)point;
/**
Returns the @c TTTAttributedLabelLink at the give point if it exists.
@discussion This can be used together with @c UIViewControllerPreviewingDelegate to peek into links.
@param point The point inside the label.
*/
- (TTTAttributedLabelLink *)linkAtPoint:(CGPoint)point;
@end
/**
The `TTTAttributedLabelDelegate` protocol defines the messages sent to an attributed label delegate when links are tapped. All of the methods of this protocol are optional.
*/
@protocol TTTAttributedLabelDelegate <NSObject>
///-----------------------------------
/// @name Responding to Link Selection
///-----------------------------------
@optional
/**
Tells the delegate that the user did select a link to a URL.
@param label The label whose link was selected.
@param url The URL for the selected link.
*/
- (void)attributedLabel:(TTTAttributedLabel *)label
didSelectLinkWithURL:(NSURL *)url;
/**
Tells the delegate that the user did select a link to an address.
@param label The label whose link was selected.
@param addressComponents The components of the address for the selected link.
*/
- (void)attributedLabel:(TTTAttributedLabel *)label
didSelectLinkWithAddress:(NSDictionary *)addressComponents;
/**
Tells the delegate that the user did select a link to a phone number.
@param label The label whose link was selected.
@param phoneNumber The phone number for the selected link.
*/
- (void)attributedLabel:(TTTAttributedLabel *)label
didSelectLinkWithPhoneNumber:(NSString *)phoneNumber;
/**
Tells the delegate that the user did select a link to a date.
@param label The label whose link was selected.
@param date The datefor the selected link.
*/
- (void)attributedLabel:(TTTAttributedLabel *)label
didSelectLinkWithDate:(NSDate *)date;
/**
Tells the delegate that the user did select a link to a date with a time zone and duration.
@param label The label whose link was selected.
@param date The date for the selected link.
@param timeZone The time zone of the date for the selected link.
@param duration The duration, in seconds from the date for the selected link.
*/
- (void)attributedLabel:(TTTAttributedLabel *)label
didSelectLinkWithDate:(NSDate *)date
timeZone:(NSTimeZone *)timeZone
duration:(NSTimeInterval)duration;
/**
Tells the delegate that the user did select a link to transit information
@param label The label whose link was selected.
@param components A dictionary containing the transit components. The currently supported keys are `NSTextCheckingAirlineKey` and `NSTextCheckingFlightKey`.
*/
- (void)attributedLabel:(TTTAttributedLabel *)label
didSelectLinkWithTransitInformation:(NSDictionary *)components;
/**
Tells the delegate that the user did select a link to a text checking result.
@discussion This method is called if no other delegate method was called, which can occur by either now implementing the method in `TTTAttributedLabelDelegate` corresponding to a particular link, or the link was added by passing an instance of a custom `NSTextCheckingResult` subclass into `-addLinkWithTextCheckingResult:`.
@param label The label whose link was selected.
@param result The custom text checking result.
*/
- (void)attributedLabel:(TTTAttributedLabel *)label
didSelectLinkWithTextCheckingResult:(NSTextCheckingResult *)result;
///---------------------------------
/// @name Responding to Long Presses
///---------------------------------
/**
* Long-press delegate methods include the CGPoint tapped within the label's coordinate space.
* This may be useful on iPad to present a popover from a specific origin point.
*/
/**
Tells the delegate that the user long-pressed a link to a URL.
@param label The label whose link was long pressed.
@param url The URL for the link.
@param point the point pressed, in the label's coordinate space
*/
- (void)attributedLabel:(TTTAttributedLabel *)label
didLongPressLinkWithURL:(NSURL *)url
atPoint:(CGPoint)point;
/**
Tells the delegate that the user long-pressed a link to an address.
@param label The label whose link was long pressed.
@param addressComponents The components of the address for the link.
@param point the point pressed, in the label's coordinate space
*/
- (void)attributedLabel:(TTTAttributedLabel *)label
didLongPressLinkWithAddress:(NSDictionary *)addressComponents
atPoint:(CGPoint)point;
/**
Tells the delegate that the user long-pressed a link to a phone number.
@param label The label whose link was long pressed.
@param phoneNumber The phone number for the link.
@param point the point pressed, in the label's coordinate space
*/
- (void)attributedLabel:(TTTAttributedLabel *)label
didLongPressLinkWithPhoneNumber:(NSString *)phoneNumber
atPoint:(CGPoint)point;
/**
Tells the delegate that the user long-pressed a link to a date.
@param label The label whose link was long pressed.
@param date The date for the selected link.
@param point the point pressed, in the label's coordinate space
*/
- (void)attributedLabel:(TTTAttributedLabel *)label
didLongPressLinkWithDate:(NSDate *)date
atPoint:(CGPoint)point;
/**
Tells the delegate that the user long-pressed a link to a date with a time zone and duration.
@param label The label whose link was long pressed.
@param date The date for the link.
@param timeZone The time zone of the date for the link.
@param duration The duration, in seconds from the date for the link.
@param point the point pressed, in the label's coordinate space
*/
- (void)attributedLabel:(TTTAttributedLabel *)label
didLongPressLinkWithDate:(NSDate *)date
timeZone:(NSTimeZone *)timeZone
duration:(NSTimeInterval)duration
atPoint:(CGPoint)point;
/**
Tells the delegate that the user long-pressed a link to transit information.
@param label The label whose link was long pressed.
@param components A dictionary containing the transit components. The currently supported keys are `NSTextCheckingAirlineKey` and `NSTextCheckingFlightKey`.
@param point the point pressed, in the label's coordinate space
*/
- (void)attributedLabel:(TTTAttributedLabel *)label
didLongPressLinkWithTransitInformation:(NSDictionary *)components
atPoint:(CGPoint)point;
/**
Tells the delegate that the user long-pressed a link to a text checking result.
@discussion Similar to `-attributedLabel:didSelectLinkWithTextCheckingResult:`, this method is called if a link is long pressed and the delegate does not implement the method corresponding to this type of link.
@param label The label whose link was long pressed.
@param result The custom text checking result.
@param point the point pressed, in the label's coordinate space
*/
- (void)attributedLabel:(TTTAttributedLabel *)label
didLongPressLinkWithTextCheckingResult:(NSTextCheckingResult *)result
atPoint:(CGPoint)point;
@end
@interface TTTAttributedLabelLink : NSObject <NSCoding>
typedef void (^TTTAttributedLabelLinkBlock) (TTTAttributedLabel *, TTTAttributedLabelLink *);
/**
An `NSTextCheckingResult` representing the link's location and type.
*/
@property (readonly, nonatomic, strong) NSTextCheckingResult *result;
/**
A dictionary containing the @c NSAttributedString attributes to be applied to the link.
*/
@property (readonly, nonatomic, copy) NSDictionary *attributes;
/**
A dictionary containing the @c NSAttributedString attributes to be applied to the link when it is in the active state.
*/
@property (readonly, nonatomic, copy) NSDictionary *activeAttributes;
/**
A dictionary containing the @c NSAttributedString attributes to be applied to the link when it is in the inactive state, which is triggered by a change in `tintColor` in iOS 7 and later.
*/
@property (readonly, nonatomic, copy) NSDictionary *inactiveAttributes;
/**
Additional information about a link for VoiceOver users. Has default values if the link's @c result is @c NSTextCheckingTypeLink, @c NSTextCheckingTypePhoneNumber, or @c NSTextCheckingTypeDate.
*/
@property (nonatomic, copy) NSString *accessibilityValue;
/**
A block called when this link is tapped.
If non-nil, tapping on this link will call this block instead of the
@c TTTAttributedLabelDelegate tap methods, which will not be called for this link.
*/
@property (nonatomic, copy) TTTAttributedLabelLinkBlock linkTapBlock;
/**
A block called when this link is long-pressed.
If non-nil, long pressing on this link will call this block instead of the
@c TTTAttributedLabelDelegate long press methods, which will not be called for this link.
*/
@property (nonatomic, copy) TTTAttributedLabelLinkBlock linkLongPressBlock;
/**
Initializes a link using the attribute dictionaries specified.
@param attributes The @c attributes property for the link.
@param activeAttributes The @c activeAttributes property for the link.
@param inactiveAttributes The @c inactiveAttributes property for the link.
@param result An @c NSTextCheckingResult representing the link's location and type.
@return The initialized link object.
*/
- (instancetype)initWithAttributes:(NSDictionary *)attributes
activeAttributes:(NSDictionary *)activeAttributes
inactiveAttributes:(NSDictionary *)inactiveAttributes
textCheckingResult:(NSTextCheckingResult *)result;
/**
Initializes a link using the attribute dictionaries set on a specified label.
@param label The attributed label from which to inherit attribute dictionaries.
@param result An @c NSTextCheckingResult representing the link's location and type.
@return The initialized link object.
*/
- (instancetype)initWithAttributesFromLabel:(TTTAttributedLabel*)label
textCheckingResult:(NSTextCheckingResult *)result;
@end

File diff suppressed because it is too large Load Diff

View File

@ -7,10 +7,6 @@
objects = {
/* Begin PBXBuildFile section */
04496BCC216252E5001F1B23 /* TTTAttributedLabel.h in Headers */ = {isa = PBXBuildFile; fileRef = 04496BCA216252E5001F1B23 /* TTTAttributedLabel.h */; settings = {ATTRIBUTES = (Public, ); }; };
04496BCF216252E5001F1B23 /* TTTAttributedLabel.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 04496BC8216252E5001F1B23 /* TTTAttributedLabel.framework */; };
04496BD0216252E5001F1B23 /* TTTAttributedLabel.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 04496BC8216252E5001F1B23 /* TTTAttributedLabel.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
04496BD52162530A001F1B23 /* TTTAttributedLabel.m in Sources */ = {isa = PBXBuildFile; fileRef = 04496BD42162530A001F1B23 /* TTTAttributedLabel.m */; };
04496BD721625361001F1B23 /* ContentLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 04496BD621625361001F1B23 /* ContentLabel.swift */; };
0461A3902163CBAE00C0A807 /* Cache.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0461A38F2163CBAE00C0A807 /* Cache.framework */; };
0461A3912163CBAE00C0A807 /* Cache.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 0461A38F2163CBAE00C0A807 /* Cache.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
@ -168,6 +164,7 @@
D6D4DDDA212518A200E1C4BB /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = D6D4DDD8212518A200E1C4BB /* LaunchScreen.storyboard */; };
D6D4DDE5212518A200E1C4BB /* TuskerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6D4DDE4212518A200E1C4BB /* TuskerTests.swift */; };
D6D4DDF0212518A200E1C4BB /* TuskerUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6D4DDEF212518A200E1C4BB /* TuskerUITests.swift */; };
D6D58DF922074B74009C8DD9 /* LinkLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6D58DF822074B74009C8DD9 /* LinkLabel.swift */; };
D6E0DC8E216EDF1E00369478 /* Previewing.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6E0DC8D216EDF1E00369478 /* Previewing.swift */; };
D6E6F26321603F8B006A8599 /* CharacterCounter.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6E6F26221603F8B006A8599 /* CharacterCounter.swift */; };
D6E6F26521604242006A8599 /* CharacterCounterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6E6F26421604242006A8599 /* CharacterCounterTests.swift */; };
@ -177,13 +174,6 @@
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
04496BCD216252E5001F1B23 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D6D4DDC4212518A000E1C4BB /* Project object */;
proxyType = 1;
remoteGlobalIDString = 04496BC7216252E5001F1B23;
remoteInfo = TTTAttributedLabel;
};
D60A549021ED515800F1F87C /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D6D4DDC4212518A000E1C4BB /* Project object */;
@ -236,7 +226,6 @@
dstSubfolderSpec = 10;
files = (
D60A549321ED515800F1F87C /* GMImagePicker.framework in Embed Frameworks */,
04496BD0216252E5001F1B23 /* TTTAttributedLabel.framework in Embed Frameworks */,
D61099C12144B0CC00432DC2 /* Pachyderm.framework in Embed Frameworks */,
D6BED170212663DA00F02DA0 /* SwiftSoup.framework in Embed Frameworks */,
D6BC874621961F73006163F1 /* Gifu.framework in Embed Frameworks */,
@ -248,10 +237,6 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
04496BC8216252E5001F1B23 /* TTTAttributedLabel.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = TTTAttributedLabel.framework; sourceTree = BUILT_PRODUCTS_DIR; };
04496BCA216252E5001F1B23 /* TTTAttributedLabel.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TTTAttributedLabel.h; sourceTree = "<group>"; };
04496BCB216252E5001F1B23 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
04496BD42162530A001F1B23 /* TTTAttributedLabel.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = TTTAttributedLabel.m; sourceTree = "<group>"; };
04496BD621625361001F1B23 /* ContentLabel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentLabel.swift; sourceTree = "<group>"; };
0461A38F2163CBAE00C0A807 /* Cache.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = Cache.framework; sourceTree = BUILT_PRODUCTS_DIR; };
04DACE8B212CB14B009840C4 /* MainTabBarViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainTabBarViewController.swift; sourceTree = "<group>"; };
@ -413,6 +398,7 @@
D6D4DDEB212518A200E1C4BB /* TuskerUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = TuskerUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
D6D4DDEF212518A200E1C4BB /* TuskerUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TuskerUITests.swift; sourceTree = "<group>"; };
D6D4DDF1212518A200E1C4BB /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
D6D58DF822074B74009C8DD9 /* LinkLabel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LinkLabel.swift; sourceTree = "<group>"; };
D6E0DC8D216EDF1E00369478 /* Previewing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Previewing.swift; sourceTree = "<group>"; };
D6E6F26221603F8B006A8599 /* CharacterCounter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CharacterCounter.swift; sourceTree = "<group>"; };
D6E6F26421604242006A8599 /* CharacterCounterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CharacterCounterTests.swift; sourceTree = "<group>"; };
@ -422,13 +408,6 @@
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
04496BC5216252E5001F1B23 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
D60A548821ED515800F1F87C /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
@ -456,7 +435,6 @@
buildActionMask = 2147483647;
files = (
D60A549221ED515800F1F87C /* GMImagePicker.framework in Frameworks */,
04496BCF216252E5001F1B23 /* TTTAttributedLabel.framework in Frameworks */,
D61099C02144B0CC00432DC2 /* Pachyderm.framework in Frameworks */,
D65A37F321472F300087646E /* SwiftSoup.framework in Frameworks */,
D6BC874521961F73006163F1 /* Gifu.framework in Frameworks */,
@ -481,16 +459,6 @@
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
04496BC9216252E5001F1B23 /* TTTAttributedLabel */ = {
isa = PBXGroup;
children = (
04496BCA216252E5001F1B23 /* TTTAttributedLabel.h */,
04496BD42162530A001F1B23 /* TTTAttributedLabel.m */,
04496BCB216252E5001F1B23 /* Info.plist */,
);
path = TTTAttributedLabel;
sourceTree = "<group>";
};
D60A548C21ED515800F1F87C /* GMImagePicker */ = {
isa = PBXGroup;
children = (
@ -921,6 +889,7 @@
D6BED1722126661300F02DA0 /* Views */ = {
isa = PBXGroup;
children = (
D6D58DF822074B74009C8DD9 /* LinkLabel.swift */,
04496BD621625361001F1B23 /* ContentLabel.swift */,
D6C693F82162E4DB007D6A6D /* StatusContentLabel.swift */,
D6C94D882139E6EC00CB5196 /* AttachmentView.swift */,
@ -968,7 +937,6 @@
D6BED16E212663DA00F02DA0 /* SwiftSoup.framework */,
D61099AC2144B0CC00432DC2 /* Pachyderm */,
D61099B92144B0CC00432DC2 /* PachydermTests */,
04496BC9216252E5001F1B23 /* TTTAttributedLabel */,
D60A548C21ED515800F1F87C /* GMImagePicker */,
D6D4DDCE212518A000E1C4BB /* Tusker */,
D6D4DDE3212518A200E1C4BB /* TuskerTests */,
@ -986,7 +954,6 @@
D6D4DDEB212518A200E1C4BB /* TuskerUITests.xctest */,
D61099AB2144B0CC00432DC2 /* Pachyderm.framework */,
D61099B32144B0CC00432DC2 /* PachydermTests.xctest */,
04496BC8216252E5001F1B23 /* TTTAttributedLabel.framework */,
D60A548B21ED515800F1F87C /* GMImagePicker.framework */,
);
name = Products;
@ -1053,14 +1020,6 @@
/* End PBXGroup section */
/* Begin PBXHeadersBuildPhase section */
04496BC3216252E5001F1B23 /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
04496BCC216252E5001F1B23 /* TTTAttributedLabel.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D60A548621ED515800F1F87C /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
@ -1085,24 +1044,6 @@
/* End PBXHeadersBuildPhase section */
/* Begin PBXNativeTarget section */
04496BC7216252E5001F1B23 /* TTTAttributedLabel */ = {
isa = PBXNativeTarget;
buildConfigurationList = 04496BD3216252E5001F1B23 /* Build configuration list for PBXNativeTarget "TTTAttributedLabel" */;
buildPhases = (
04496BC3216252E5001F1B23 /* Headers */,
04496BC4216252E5001F1B23 /* Sources */,
04496BC5216252E5001F1B23 /* Frameworks */,
04496BC6216252E5001F1B23 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = TTTAttributedLabel;
productName = TTTAttributedLabel;
productReference = 04496BC8216252E5001F1B23 /* TTTAttributedLabel.framework */;
productType = "com.apple.product-type.framework";
};
D60A548A21ED515800F1F87C /* GMImagePicker */ = {
isa = PBXNativeTarget;
buildConfigurationList = D60A549421ED515800F1F87C /* Build configuration list for PBXNativeTarget "GMImagePicker" */;
@ -1171,7 +1112,6 @@
);
dependencies = (
D61099BF2144B0CC00432DC2 /* PBXTargetDependency */,
04496BCE216252E5001F1B23 /* PBXTargetDependency */,
D60A549121ED515800F1F87C /* PBXTargetDependency */,
);
name = Tusker;
@ -1225,9 +1165,6 @@
LastUpgradeCheck = 1010;
ORGANIZATIONNAME = Shadowfacts;
TargetAttributes = {
04496BC7216252E5001F1B23 = {
CreatedOnToolsVersion = 10.1;
};
D60A548A21ED515800F1F87C = {
CreatedOnToolsVersion = 10.1;
};
@ -1276,20 +1213,12 @@
D6D4DDEA212518A200E1C4BB /* TuskerUITests */,
D61099AA2144B0CC00432DC2 /* Pachyderm */,
D61099B22144B0CC00432DC2 /* PachydermTests */,
04496BC7216252E5001F1B23 /* TTTAttributedLabel */,
D60A548A21ED515800F1F87C /* GMImagePicker */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
04496BC6216252E5001F1B23 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
D60A548921ED515800F1F87C /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
@ -1366,14 +1295,6 @@
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
04496BC4216252E5001F1B23 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
04496BD52162530A001F1B23 /* TTTAttributedLabel.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D60A548721ED515800F1F87C /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
@ -1446,6 +1367,7 @@
D6757A822157E8FA00721E32 /* XCBSession.swift in Sources */,
04DACE8C212CB14B009840C4 /* MainTabBarViewController.swift in Sources */,
D6C693F92162E4DB007D6A6D /* StatusContentLabel.swift in Sources */,
D6D58DF922074B74009C8DD9 /* LinkLabel.swift in Sources */,
D6285B5121EA6E6E00FE4B39 /* AdvancedTableViewController.swift in Sources */,
D667E5F52135BCD50057A976 /* ConversationTableViewController.swift in Sources */,
D6F953F021251A2900CF0F2B /* MastodonController.swift in Sources */,
@ -1533,11 +1455,6 @@
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
04496BCE216252E5001F1B23 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 04496BC7216252E5001F1B23 /* TTTAttributedLabel */;
targetProxy = 04496BCD216252E5001F1B23 /* PBXContainerItemProxy */;
};
D60A549121ED515800F1F87C /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = D60A548A21ED515800F1F87C /* GMImagePicker */;
@ -1646,62 +1563,6 @@
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
04496BD1216252E5001F1B23 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_IDENTITY = "";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEFINES_MODULE = YES;
DEVELOPMENT_TEAM = HGYVAQA9FW;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
INFOPLIST_FILE = TTTAttributedLabel/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 12.1;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = net.shadowfacts.TTTAttributedLabel;
PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Debug;
};
04496BD2216252E5001F1B23 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_IDENTITY = "";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEFINES_MODULE = YES;
DEVELOPMENT_TEAM = HGYVAQA9FW;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
INFOPLIST_FILE = TTTAttributedLabel/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 12.1;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = net.shadowfacts.TTTAttributedLabel;
PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Release;
};
D60A549521ED515800F1F87C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
@ -2102,15 +1963,6 @@
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
04496BD3216252E5001F1B23 /* Build configuration list for PBXNativeTarget "TTTAttributedLabel" */ = {
isa = XCConfigurationList;
buildConfigurations = (
04496BD1216252E5001F1B23 /* Debug */,
04496BD2216252E5001F1B23 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
D60A549421ED515800F1F87C /* Build configuration list for PBXNativeTarget "GMImagePicker" */ = {
isa = XCConfigurationList;
buildConfigurations = (

View File

@ -126,6 +126,7 @@ extension TuskerNavigationDelegate where Self: UIViewController {
private func moreOptions(forURL url: URL) -> UIAlertController {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alert.title = url.absoluteString
alert.addAction(UIAlertAction(title: "Open in Safari", style: .default, handler: { (_) in
let vc = SFSafariViewController(url: url)
self.present(vc, animated: true)

View File

@ -12,16 +12,10 @@ import TTTAttributedLabel
import Pachyderm
import SwiftSoup
class ContentLabel: TTTAttributedLabel {
class ContentLabel: LinkLabel {
var navigationDelegate: TuskerNavigationDelegate?
override func awakeFromNib() {
super.awakeFromNib()
isUserInteractionEnabled = true
}
// MARK: - HTML Parsing
func setTextFromHtml(_ html: String) {
let doc = try! SwiftSoup.parse(html)
@ -36,21 +30,17 @@ class ContentLabel: TTTAttributedLabel {
mutAttrString.trimTrailingCharactersInSet(.whitespacesAndNewlines)
mutAttrString.addAttribute(.font, value: font, range: NSRange(location: 0, length: mutAttrString.length))
self.text = mutAttrString
let linkAttributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.blue,
]
for (range, url) in links {
let result = NSTextCheckingResult.linkCheckingResult(range: range, url: url)
let link = TTTAttributedLabelLink(attributes: [
NSAttributedString.Key.foregroundColor: UIColor.blue
], activeAttributes: [
kTTTBackgroundFillColorAttributeName: UIColor(displayP3Red: 0.9, green: 0.9, blue: 0.9, alpha: 1),
kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2),
kTTTBackgroundCornerRadiusAttributeName: NSNumber(value: 5)
], inactiveAttributes: [:], textCheckingResult: result)!
link.linkTapBlock = self.linkTapped
link.linkLongPressBlock = self.linkLongPressed
addLink(link)
mutAttrString.addAttributes(linkAttributes, range: range)
self.links.append(Link(range: range, url: url))
}
self.attributedText = mutAttrString
}
private func attributedTextForHTMLNode(_ node: Node) -> (NSAttributedString, [NSRange: URL]) {
@ -90,12 +80,9 @@ class ContentLabel: TTTAttributedLabel {
}
}
func getViewController(forLinkAt point: CGPoint) -> UIViewController? {
guard let link = link(at: point),
let url = link.result.url else {
return nil
}
let text = (self.text as! NSString).substring(with: link.result.range)
func getViewController(forLink url: URL, inRange range: NSRange) -> UIViewController {
let text = (self.text! as NSString).substring(with: range)
if let mention = getMention(for: url, text: text) {
return ProfileTableViewController(accountID: mention.id)
} else if let tag = getHashtag(for: url, text: text) {
@ -105,27 +92,29 @@ class ContentLabel: TTTAttributedLabel {
}
}
// MARK: - Interaction
func linkTapped(_ label: TTTAttributedLabel!, _ link: TTTAttributedLabelLink!) {
guard let navigationDelegate = navigationDelegate,
let url = link.result.url else {
return
func getViewController(forLinkAt point: CGPoint) -> UIViewController? {
guard let link = getLink(atPoint: point) else {
return nil
}
let text = (self.text as! NSString).substring(with: link.result.range)
if let mention = getMention(for: url, text: text) {
navigationDelegate.selected(mention: mention)
} else if let tag = getHashtag(for: url, text: text) {
navigationDelegate.selected(tag: tag)
return getViewController(forLink: link.url, inRange: link.range)
}
// MARK: - Interaction
override func linkTapped(_ link: LinkLabel.Link) {
let text = (self.text! as NSString).substring(with: link.range)
if let mention = getMention(for: link.url, text: text) {
navigationDelegate?.selected(mention: mention)
} else if let tag = getHashtag(for: link.url, text: text) {
navigationDelegate?.selected(tag: tag)
} else {
navigationDelegate.selected(url: url)
navigationDelegate?.selected(url: link.url)
}
}
func linkLongPressed(_ label: TTTAttributedLabel!, _ link: TTTAttributedLabelLink!) {
guard let url = link.result.url else {
return
}
navigationDelegate?.showMoreOptions(forURL: url)
override func linkLongPressed(_ link: LinkLabel.Link) {
navigationDelegate?.showMoreOptions(forURL: link.url)
}
// MARK: - Navigation

View File

@ -0,0 +1,181 @@
//
// LinkLabel.swift
// Tusker
//
// Created by Shadowfacts on 2/3/19.
// Copyright © 2019 Shadowfacts. All rights reserved.
//
import UIKit
class LinkLabel: UILabel {
typealias Link = (range: NSRange, url: URL)
let layoutManager = NSLayoutManager()
let textContainer = NSTextContainer(size: .zero)
var textStorage: NSTextStorage!
var links = [Link]()
var selectedLinkAttributes: [NSAttributedString.Key: Any] = [
.backgroundColor: UIColor(hue: 0, saturation: 0, brightness: 0.9, alpha: 1)
]
var selectedLinkRange: NSRange? {
didSet {
if let oldValue = oldValue {
removeSelectedLinkAttributes(oldValue)
}
if let newValue = selectedLinkRange {
addSelectedLinkAttributes(newValue)
}
}
}
override var attributedText: NSAttributedString? {
didSet {
guard let attributedText = attributedText else { return }
textStorage = NSTextStorage(attributedString: attributedText)
textStorage.addLayoutManager(layoutManager)
}
}
override var text: String? {
willSet {
fatalError("LinkLabel does not support non-attributed text")
}
}
override func awakeFromNib() {
super.awakeFromNib()
isUserInteractionEnabled = true
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(labelTapped(_:)))
tapRecognizer.delegate = self
addGestureRecognizer(tapRecognizer)
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(labelLongPressed(_:)))
longPressRecognizer.delegate = self
addGestureRecognizer(longPressRecognizer)
layoutManager.addTextContainer(textContainer)
textContainer.lineFragmentPadding = 0.0
textContainer.lineBreakMode = lineBreakMode
textContainer.maximumNumberOfLines = numberOfLines
}
override func layoutSubviews() {
super.layoutSubviews()
textContainer.size = bounds.size
}
func getLink(atPoint point: CGPoint) -> Link? {
let labelSize = bounds.size
let textBoundingBox = layoutManager.usedRect(for: textContainer)
let textContainerOffset = CGPoint(x: (labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x,
y: (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)
let locationOfTouchInTextContainer = CGPoint(x: point.x - textContainerOffset.x,
y: point.y - textContainerOffset.y)
// let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
let indexOfCharacter = layoutManager.glyphIndex(for: locationOfTouchInTextContainer, in: textContainer)
if let link = links.first(where: { $0.range.contains(indexOfCharacter) }) {
return link
} else {
return nil
}
}
func addSelectedLinkAttributes(_ range: NSRange) {
let mutAttrString = NSMutableAttributedString(attributedString: attributedText!)
mutAttrString.addAttributes(selectedLinkAttributes, range: range)
self.attributedText = mutAttrString
setNeedsDisplay()
}
func removeSelectedLinkAttributes(_ range: NSRange) {
let mutAttrString = NSMutableAttributedString(attributedString: attributedText!)
selectedLinkAttributes.keys.forEach { mutAttrString.removeAttribute($0, range: range) }
self.attributedText = mutAttrString
setNeedsDisplay()
}
// MARK: - Interaction
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first, onTouch(touch) {
return
}
super.touchesBegan(touches, with: event)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first, onTouch(touch) {
return
}
super.touchesMoved(touches, with: event)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first, onTouch(touch) {
return
}
super.touchesEnded(touches, with: event)
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first, onTouch(touch) {
return
}
super.touchesCancelled(touches, with: event)
}
func onTouch(_ touch: UITouch) -> Bool {
let location = touch.location(in: self)
let link = getLink(atPoint: location)
switch touch.phase {
case .began, .moved:
selectedLinkRange = link?.range
case .cancelled, .ended:
selectedLinkRange = nil
default:
break
}
return link != nil
}
@objc func labelTapped(_ recognizer: UITapGestureRecognizer) {
let location = recognizer.location(in: self)
guard let link = getLink(atPoint: location) else {
return
}
linkTapped(link)
}
@objc func labelLongPressed(_ recognizer: UILongPressGestureRecognizer) {
let location = recognizer.location(in: self)
guard let link = getLink(atPoint: location) else {
return
}
linkLongPressed(link)
}
func linkTapped(_ link: Link) {
}
func linkLongPressed(_ link: Link) {
}
}
extension LinkLabel: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
let location = touch.location(in: self)
let link = getLink(atPoint: location)
return link != nil
}
}