Repository: coderwhy/HYLabel Branch: master Commit: 99ee05319680 Files: 27 Total size: 78.4 KB Directory structure: gitextract_abjvbfjq/ ├── .gitignore ├── HYLabel/ │ ├── HYLabel/ │ │ ├── HYLabel.h │ │ └── Info.plist │ ├── HYLabel.xcodeproj/ │ │ └── project.pbxproj │ └── Source/ │ └── HYLabel.swift ├── HYLabel.podspec ├── HYLabel.xcworkspace/ │ └── contents.xcworkspacedata ├── HYLabelDemo-Swift/ │ ├── HYLabelDemo-Swift/ │ │ ├── AppDelegate.swift │ │ ├── Assets.xcassets/ │ │ │ └── AppIcon.appiconset/ │ │ │ └── Contents.json │ │ ├── Base.lproj/ │ │ │ ├── LaunchScreen.storyboard │ │ │ └── Main.storyboard │ │ ├── Info.plist │ │ └── ViewController.swift │ └── HYLabelDemo-Swift.xcodeproj/ │ └── project.pbxproj ├── HYLabelDemoOC/ │ ├── HYLabelDemoOC/ │ │ ├── AppDelegate.h │ │ ├── AppDelegate.m │ │ ├── Assets.xcassets/ │ │ │ └── AppIcon.appiconset/ │ │ │ └── Contents.json │ │ ├── Base.lproj/ │ │ │ ├── LaunchScreen.storyboard │ │ │ └── Main.storyboard │ │ ├── Info.plist │ │ ├── Source/ │ │ │ └── HYLabel.swift │ │ ├── ViewController.h │ │ ├── ViewController.m │ │ └── main.m │ └── HYLabelDemoOC.xcodeproj/ │ └── project.pbxproj ├── LICENSE └── README.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .DS_Store # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore ## Build generated build/ DerivedData ## Various settings *.pbxuser !default.pbxuser *.mode1v3 !default.mode1v3 *.mode2v3 !default.mode2v3 *.perspectivev3 !default.perspectivev3 xcuserdata ## Other *.xccheckout *.moved-aside *.xcuserstate *.xcscmblueprint ## Obj-C/Swift specific *.hmap *.ipa ## Playgrounds timeline.xctimeline playground.xcworkspace # Swift Package Manager # # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ .build/ # CocoaPods # # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control # # Pods/ # Carthage # # Add this line if you want to avoid checking in source code from Carthage dependencies. # Carthage/Checkouts Carthage/Build # fastlane # # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the # screenshots whenever they are needed. # For more information about the recommended setup visit: # https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md fastlane/report.xml fastlane/screenshots ================================================ FILE: HYLabel/HYLabel/HYLabel.h ================================================ // // HYLabel.h // HYLabel // // Created by apple on 16/3/9. // Copyright © 2016年 xiaomage. All rights reserved. // #import //! Project version number for HYLabel. FOUNDATION_EXPORT double HYLabelVersionNumber; //! Project version string for HYLabel. FOUNDATION_EXPORT const unsigned char HYLabelVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import ================================================ FILE: HYLabel/HYLabel/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType FMWK CFBundleShortVersionString 1.0 CFBundleSignature ???? CFBundleVersion $(CURRENT_PROJECT_VERSION) NSPrincipalClass ================================================ FILE: HYLabel/HYLabel.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ 187A8A111C8FC0EB00D8DA51 /* HYLabel.h in Headers */ = {isa = PBXBuildFile; fileRef = 187A8A101C8FC0EB00D8DA51 /* HYLabel.h */; settings = {ATTRIBUTES = (Public, ); }; }; 187A8A1A1C8FC15300D8DA51 /* HYLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 187A8A191C8FC15300D8DA51 /* HYLabel.swift */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ 187A8A0D1C8FC0EB00D8DA51 /* HYLabel.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = HYLabel.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 187A8A101C8FC0EB00D8DA51 /* HYLabel.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = HYLabel.h; sourceTree = ""; }; 187A8A121C8FC0EB00D8DA51 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 187A8A191C8FC15300D8DA51 /* HYLabel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HYLabel.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 187A8A091C8FC0EB00D8DA51 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 187A8A031C8FC0EB00D8DA51 = { isa = PBXGroup; children = ( 187A8A0F1C8FC0EB00D8DA51 /* HYLabel */, 187A8A0E1C8FC0EB00D8DA51 /* Products */, ); sourceTree = ""; }; 187A8A0E1C8FC0EB00D8DA51 /* Products */ = { isa = PBXGroup; children = ( 187A8A0D1C8FC0EB00D8DA51 /* HYLabel.framework */, ); name = Products; sourceTree = ""; }; 187A8A0F1C8FC0EB00D8DA51 /* HYLabel */ = { isa = PBXGroup; children = ( 187A8A181C8FC13E00D8DA51 /* Source */, 187A8A101C8FC0EB00D8DA51 /* HYLabel.h */, 187A8A121C8FC0EB00D8DA51 /* Info.plist */, ); path = HYLabel; sourceTree = ""; }; 187A8A181C8FC13E00D8DA51 /* Source */ = { isa = PBXGroup; children = ( 187A8A191C8FC15300D8DA51 /* HYLabel.swift */, ); path = Source; sourceTree = SOURCE_ROOT; }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ 187A8A0A1C8FC0EB00D8DA51 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( 187A8A111C8FC0EB00D8DA51 /* HYLabel.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXHeadersBuildPhase section */ /* Begin PBXNativeTarget section */ 187A8A0C1C8FC0EB00D8DA51 /* HYLabel */ = { isa = PBXNativeTarget; buildConfigurationList = 187A8A151C8FC0EB00D8DA51 /* Build configuration list for PBXNativeTarget "HYLabel" */; buildPhases = ( 187A8A081C8FC0EB00D8DA51 /* Sources */, 187A8A091C8FC0EB00D8DA51 /* Frameworks */, 187A8A0A1C8FC0EB00D8DA51 /* Headers */, 187A8A0B1C8FC0EB00D8DA51 /* Resources */, ); buildRules = ( ); dependencies = ( ); name = HYLabel; productName = HYLabel; productReference = 187A8A0D1C8FC0EB00D8DA51 /* HYLabel.framework */; productType = "com.apple.product-type.framework"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 187A8A041C8FC0EB00D8DA51 /* Project object */ = { isa = PBXProject; attributes = { LastUpgradeCheck = 0720; ORGANIZATIONNAME = xiaomage; TargetAttributes = { 187A8A0C1C8FC0EB00D8DA51 = { CreatedOnToolsVersion = 7.2; }; }; }; buildConfigurationList = 187A8A071C8FC0EB00D8DA51 /* Build configuration list for PBXProject "HYLabel" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( en, ); mainGroup = 187A8A031C8FC0EB00D8DA51; productRefGroup = 187A8A0E1C8FC0EB00D8DA51 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 187A8A0C1C8FC0EB00D8DA51 /* HYLabel */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 187A8A0B1C8FC0EB00D8DA51 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 187A8A081C8FC0EB00D8DA51 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 187A8A1A1C8FC15300D8DA51 /* HYLabel.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin XCBuildConfiguration section */ 187A8A131C8FC0EB00D8DA51 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 9.2; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; 187A8A141C8FC0EB00D8DA51 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 9.2; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; 187A8A161C8FC0EB00D8DA51 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { CLANG_ENABLE_MODULES = YES; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; INFOPLIST_FILE = HYLabel/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.520it.HYLabel; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; }; name = Debug; }; 187A8A171C8FC0EB00D8DA51 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { CLANG_ENABLE_MODULES = YES; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; INFOPLIST_FILE = HYLabel/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.520it.HYLabel; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 187A8A071C8FC0EB00D8DA51 /* Build configuration list for PBXProject "HYLabel" */ = { isa = XCConfigurationList; buildConfigurations = ( 187A8A131C8FC0EB00D8DA51 /* Debug */, 187A8A141C8FC0EB00D8DA51 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 187A8A151C8FC0EB00D8DA51 /* Build configuration list for PBXNativeTarget "HYLabel" */ = { isa = XCConfigurationList; buildConfigurations = ( 187A8A161C8FC0EB00D8DA51 /* Debug */, 187A8A171C8FC0EB00D8DA51 /* Release */, ); defaultConfigurationIsVisible = 0; }; /* End XCConfigurationList section */ }; rootObject = 187A8A041C8FC0EB00D8DA51 /* Project object */; } ================================================ FILE: HYLabel/Source/HYLabel.swift ================================================ // // HYLabel.swift // HYLabel // // Created by apple on 16/3/8. // Copyright © 2016年 xiaomage. All rights reserved. // import UIKit enum TapHandlerType : Int { case noneHandle = 0 case userHandle = 1 case topicHandle = 2 case linkHandle = 3 } public class HYLabel: UILabel { // MARK:- 属性 // 重写系统的属性 override public var text : String? { didSet { prepareText() } } override public var attributedText: NSAttributedString? { didSet { prepareText() } } override public var font: UIFont! { didSet { prepareText() } } override public var textColor: UIColor! { didSet { prepareText() } } public var matchTextColor : UIColor = UIColor(red: 87 / 255.0, green: 196 / 255.0, blue: 251 / 255.0, alpha: 1.0) { didSet { prepareText() } } // 懒加载属性 private lazy var textStorage : NSTextStorage = NSTextStorage() // NSMutableAttributeString的子类 private lazy var layoutManager : NSLayoutManager = NSLayoutManager() // 布局管理者 private lazy var textContainer : NSTextContainer = NSTextContainer() // 容器,需要设置容器的大小 // 用于记录下标值 private lazy var linkRanges : [NSRange] = [NSRange]() private lazy var userRanges : [NSRange] = [NSRange]() private lazy var topicRanges : [NSRange] = [NSRange]() // 用于记录用户选中的range private var selectedRange : NSRange? // 用户记录点击还是松开 private var isSelected : Bool = false // 闭包属性,用于回调 private var tapHandlerType : TapHandlerType = TapHandlerType.noneHandle public typealias HYTapHandler = (HYLabel, String, NSRange) -> Void public var linkTapHandler : HYTapHandler? public var topicTapHandler : HYTapHandler? public var userTapHandler : HYTapHandler? // MARK:- 构造函数 override init(frame: CGRect) { super.init(frame: frame) prepareTextSystem() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepareTextSystem() } // MARK:- 布局子控件 override public func layoutSubviews() { super.layoutSubviews() // 设置容器的大小为Label的尺寸 textContainer.size = frame.size } // MARK:- 重写drawTextInRect方法 override public func drawTextInRect(rect: CGRect) { // 1.绘制背景 if selectedRange != nil { // 2.0.确定颜色 let selectedColor = isSelected ? UIColor(white: 0.7, alpha: 0.2) : UIColor.clearColor() // 2.1.设置颜色 textStorage.addAttribute(NSBackgroundColorAttributeName, value: selectedColor, range: selectedRange!) // 2.2.绘制背景 layoutManager.drawBackgroundForGlyphRange(selectedRange!, atPoint: CGPoint(x: 0, y: 0)) } // 2.绘制字形 // 需要绘制的范围 let range = NSRange(location: 0, length: textStorage.length) layoutManager.drawGlyphsForGlyphRange(range, atPoint: CGPointZero) } } extension HYLabel { /// 准备文本系统 private func prepareTextSystem() { // 0.准备文本 prepareText() // 1.将布局添加到storeage中 textStorage.addLayoutManager(layoutManager) // 2.将容器添加到布局中 layoutManager.addTextContainer(textContainer) // 3.让label可以和用户交互 userInteractionEnabled = true // 4.设置间距为0 textContainer.lineFragmentPadding = 0 } /// 准备文本 private func prepareText() { // 1.准备字符串 var attrString : NSAttributedString? if attributedText != nil { attrString = attributedText } else if text != nil { attrString = NSAttributedString(string: text!) } else { attrString = NSAttributedString(string: "") } selectedRange = nil // 2.设置换行模型 let attrStringM = addLineBreak(attrString!) attrStringM.addAttribute(NSFontAttributeName, value: font, range: NSRange(location: 0, length: attrStringM.length)) // 3.设置textStorage的内容 textStorage.setAttributedString(attrStringM) // 4.匹配URL if let linkRanges = getLinkRanges() { self.linkRanges = linkRanges for range in linkRanges { textStorage.addAttribute(NSForegroundColorAttributeName, value: matchTextColor, range: range) } } // 5.匹配@用户 if let userRanges = getRanges("@[\\u4e00-\\u9fa5a-zA-Z0-9_-]*") { self.userRanges = userRanges for range in userRanges { textStorage.addAttribute(NSForegroundColorAttributeName, value: matchTextColor, range: range) } } // 6.匹配话题## if let topicRanges = getRanges("#.*?#") { self.topicRanges = topicRanges for range in topicRanges { textStorage.addAttribute(NSForegroundColorAttributeName, value: matchTextColor, range: range) } } setNeedsDisplay() } } // MARK:- 字符串匹配封装 extension HYLabel { private func getRanges(pattern : String) -> [NSRange]? { // 创建正则表达式对象 guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else { return nil } return getRangesFromResult(regex) } private func getLinkRanges() -> [NSRange]? { // 创建正则表达式 guard let detector = try? NSDataDetector(types: NSTextCheckingType.Link.rawValue) else { return nil } return getRangesFromResult(detector) } private func getRangesFromResult(regex : NSRegularExpression) -> [NSRange] { // 1.匹配结果 let results = regex.matchesInString(textStorage.string, options: [], range: NSRange(location: 0, length: textStorage.length)) // 2.遍历结果 var ranges = [NSRange]() for res in results { ranges.append(res.range) } return ranges } } // MARK:- 点击交互的封装 extension HYLabel { override public func touchesBegan(touches: Set, withEvent event: UIEvent?) { // 0.记录点击 isSelected = true // 1.获取用户点击的点 let selectedPoint = touches.first!.locationInView(self) // 2.获取该点所在的字符串的range selectedRange = getSelectRange(selectedPoint) // 3.是否处理了事件 if selectedRange == nil { super.touchesBegan(touches, withEvent: event) } } override public func touchesEnded(touches: Set, withEvent event: UIEvent?) { if selectedRange == nil { super.touchesBegan(touches, withEvent: event) return } // 0.记录松开 isSelected = false // 2.重新绘制 setNeedsDisplay() // 3.取出内容 let contentText = (textStorage.string as NSString).substringWithRange(selectedRange!) // 3.回调 switch tapHandlerType { case .linkHandle: if linkTapHandler != nil { linkTapHandler!(self, contentText, selectedRange!) } case .topicHandle: if topicTapHandler != nil { topicTapHandler!(self, contentText, selectedRange!) } case .userHandle: if userTapHandler != nil { userTapHandler!(self, contentText, selectedRange!) } default: break } } private func getSelectRange(selectedPoint : CGPoint) -> NSRange? { // 0.如果属性字符串为nil,则不需要判断 if textStorage.length == 0 { return nil } // 1.获取选中点所在的下标值(index) let index = layoutManager.glyphIndexForPoint(selectedPoint, inTextContainer: textContainer) // 2.判断下标在什么内 // 2.1.判断是否是一个链接 for linkRange in linkRanges { if index > linkRange.location && index < linkRange.location + linkRange.length { setNeedsDisplay() tapHandlerType = .linkHandle return linkRange } } // 2.2.判断是否是一个@用户 for userRange in userRanges { if index > userRange.location && index < userRange.location + userRange.length { setNeedsDisplay() tapHandlerType = .userHandle return userRange } } // 2.3.判断是否是一个#话题# for topicRange in topicRanges { if index > topicRange.location && index < topicRange.location + topicRange.length { setNeedsDisplay() tapHandlerType = .topicHandle return topicRange } } return nil } } // MARK:- 补充 extension HYLabel { /// 如果用户没有设置lineBreak,则所有内容会绘制到同一行中,因此需要主动设置 private func addLineBreak(attrString: NSAttributedString) -> NSMutableAttributedString { let attrStringM = NSMutableAttributedString(attributedString: attrString) if attrStringM.length == 0 { return attrStringM } var range = NSRange(location: 0, length: 0) var attributes = attrStringM.attributesAtIndex(0, effectiveRange: &range) var paragraphStyle = attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle if paragraphStyle != nil { paragraphStyle!.lineBreakMode = NSLineBreakMode.ByWordWrapping } else { paragraphStyle = NSMutableParagraphStyle() paragraphStyle!.lineBreakMode = NSLineBreakMode.ByWordWrapping attributes[NSParagraphStyleAttributeName] = paragraphStyle attrStringM.setAttributes(attributes, range: range) } return attrStringM } } ================================================ FILE: HYLabel.podspec ================================================ Pod::Spec.new do |s| s.name = 'HYLabel' s.version = '1.0.1' s.summary = '用于识别Label中的@用户-话题##-链接' s.homepage = 'https://github.com/coderwhy/HYLabel' s.license = 'MIT' s.authors = {'coderwhy' => '372623326@qq.com'} s.platform = :ios, '8.0' s.source = {:git => 'https://github.com/coderwhy/HYLabel.git', :tag => s.version} s.source_files = 'HYLabel/Source/*.swift' s.framework = 'UIKit' s.requires_arc = true end ================================================ FILE: HYLabel.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: HYLabelDemo-Swift/HYLabelDemo-Swift/AppDelegate.swift ================================================ // // AppDelegate.swift // HYLabelDemo-Swift // // Created by apple on 16/3/9. // Copyright © 2016年 xiaomage. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } ================================================ FILE: HYLabelDemo-Swift/HYLabelDemo-Swift/Assets.xcassets/AppIcon.appiconset/Contents.json ================================================ { "images" : [ { "idiom" : "iphone", "size" : "29x29", "scale" : "2x" }, { "idiom" : "iphone", "size" : "29x29", "scale" : "3x" }, { "idiom" : "iphone", "size" : "40x40", "scale" : "2x" }, { "idiom" : "iphone", "size" : "40x40", "scale" : "3x" }, { "idiom" : "iphone", "size" : "60x60", "scale" : "2x" }, { "idiom" : "iphone", "size" : "60x60", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: HYLabelDemo-Swift/HYLabelDemo-Swift/Base.lproj/LaunchScreen.storyboard ================================================ ================================================ FILE: HYLabelDemo-Swift/HYLabelDemo-Swift/Base.lproj/Main.storyboard ================================================ ================================================ FILE: HYLabelDemo-Swift/HYLabelDemo-Swift/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType APPL CFBundleShortVersionString 1.0 CFBundleSignature ???? CFBundleVersion 1 LSRequiresIPhoneOS UILaunchStoryboardName LaunchScreen UIMainStoryboardFile Main UIRequiredDeviceCapabilities armv7 UISupportedInterfaceOrientations UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight ================================================ FILE: HYLabelDemo-Swift/HYLabelDemo-Swift/ViewController.swift ================================================ // // ViewController.swift // HYLabelDemo-Swift // // Created by apple on 16/3/9. // Copyright © 2016年 xiaomage. All rights reserved. // import UIKit import HYLabel class ViewController: UIViewController { @IBOutlet weak var demoLabel: HYLabel! override func viewDidLoad() { super.viewDidLoad() // 监听@谁谁谁的点击 demoLabel.userTapHandler = { (label, user, range) in print(label) print(user) print(range) } // 监听链接的点击 demoLabel.linkTapHandler = { (label, link, range) in print(label) print(link) print(range) } // 监听话题的点击 demoLabel.topicTapHandler = { (label, topic, range) in print(label) print(topic) print(range) } } override func touchesBegan(touches: Set, withEvent event: UIEvent?) { demoLabel.text = "作者:@coderwhy 话题:#Label字符串识别# 网址:http://www.520it.com" } } ================================================ FILE: HYLabelDemo-Swift/HYLabelDemo-Swift.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ 187A89F21C8FC0A300D8DA51 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 187A89F11C8FC0A300D8DA51 /* AppDelegate.swift */; }; 187A89F41C8FC0A300D8DA51 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 187A89F31C8FC0A300D8DA51 /* ViewController.swift */; }; 187A89F71C8FC0A300D8DA51 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 187A89F51C8FC0A300D8DA51 /* Main.storyboard */; }; 187A89F91C8FC0A300D8DA51 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 187A89F81C8FC0A300D8DA51 /* Assets.xcassets */; }; 187A89FC1C8FC0A300D8DA51 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 187A89FA1C8FC0A300D8DA51 /* LaunchScreen.storyboard */; }; 187A8A1D1C8FC2E200D8DA51 /* HYLabel.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 187A8A1C1C8FC2E200D8DA51 /* HYLabel.framework */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ 187A89EE1C8FC0A300D8DA51 /* HYLabelDemo-Swift.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "HYLabelDemo-Swift.app"; sourceTree = BUILT_PRODUCTS_DIR; }; 187A89F11C8FC0A300D8DA51 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 187A89F31C8FC0A300D8DA51 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; 187A89F61C8FC0A300D8DA51 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 187A89F81C8FC0A300D8DA51 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 187A89FB1C8FC0A300D8DA51 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 187A89FD1C8FC0A300D8DA51 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 187A8A1C1C8FC2E200D8DA51 /* HYLabel.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = HYLabel.framework; path = "../HYLabel/build/Debug-iphoneos/HYLabel.framework"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 187A89EB1C8FC0A300D8DA51 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 187A8A1D1C8FC2E200D8DA51 /* HYLabel.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 187A89E51C8FC0A300D8DA51 = { isa = PBXGroup; children = ( 187A8A1C1C8FC2E200D8DA51 /* HYLabel.framework */, 187A89F01C8FC0A300D8DA51 /* HYLabelDemo-Swift */, 187A89EF1C8FC0A300D8DA51 /* Products */, ); sourceTree = ""; }; 187A89EF1C8FC0A300D8DA51 /* Products */ = { isa = PBXGroup; children = ( 187A89EE1C8FC0A300D8DA51 /* HYLabelDemo-Swift.app */, ); name = Products; sourceTree = ""; }; 187A89F01C8FC0A300D8DA51 /* HYLabelDemo-Swift */ = { isa = PBXGroup; children = ( 187A89F11C8FC0A300D8DA51 /* AppDelegate.swift */, 187A89F31C8FC0A300D8DA51 /* ViewController.swift */, 187A89F51C8FC0A300D8DA51 /* Main.storyboard */, 187A89F81C8FC0A300D8DA51 /* Assets.xcassets */, 187A89FA1C8FC0A300D8DA51 /* LaunchScreen.storyboard */, 187A89FD1C8FC0A300D8DA51 /* Info.plist */, ); path = "HYLabelDemo-Swift"; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 187A89ED1C8FC0A300D8DA51 /* HYLabelDemo-Swift */ = { isa = PBXNativeTarget; buildConfigurationList = 187A8A001C8FC0A300D8DA51 /* Build configuration list for PBXNativeTarget "HYLabelDemo-Swift" */; buildPhases = ( 187A89EA1C8FC0A300D8DA51 /* Sources */, 187A89EB1C8FC0A300D8DA51 /* Frameworks */, 187A89EC1C8FC0A300D8DA51 /* Resources */, ); buildRules = ( ); dependencies = ( ); name = "HYLabelDemo-Swift"; productName = "HYLabelDemo-Swift"; productReference = 187A89EE1C8FC0A300D8DA51 /* HYLabelDemo-Swift.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 187A89E61C8FC0A300D8DA51 /* Project object */ = { isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0720; LastUpgradeCheck = 0720; ORGANIZATIONNAME = xiaomage; TargetAttributes = { 187A89ED1C8FC0A300D8DA51 = { CreatedOnToolsVersion = 7.2; }; }; }; buildConfigurationList = 187A89E91C8FC0A300D8DA51 /* Build configuration list for PBXProject "HYLabelDemo-Swift" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = 187A89E51C8FC0A300D8DA51; productRefGroup = 187A89EF1C8FC0A300D8DA51 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 187A89ED1C8FC0A300D8DA51 /* HYLabelDemo-Swift */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 187A89EC1C8FC0A300D8DA51 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 187A89FC1C8FC0A300D8DA51 /* LaunchScreen.storyboard in Resources */, 187A89F91C8FC0A300D8DA51 /* Assets.xcassets in Resources */, 187A89F71C8FC0A300D8DA51 /* Main.storyboard in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 187A89EA1C8FC0A300D8DA51 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 187A89F41C8FC0A300D8DA51 /* ViewController.swift in Sources */, 187A89F21C8FC0A300D8DA51 /* AppDelegate.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXVariantGroup section */ 187A89F51C8FC0A300D8DA51 /* Main.storyboard */ = { isa = PBXVariantGroup; children = ( 187A89F61C8FC0A300D8DA51 /* Base */, ); name = Main.storyboard; sourceTree = ""; }; 187A89FA1C8FC0A300D8DA51 /* LaunchScreen.storyboard */ = { isa = PBXVariantGroup; children = ( 187A89FB1C8FC0A300D8DA51 /* Base */, ); name = LaunchScreen.storyboard; sourceTree = ""; }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ 187A89FE1C8FC0A300D8DA51 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 9.2; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; }; name = Debug; }; 187A89FF1C8FC0A300D8DA51 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 9.2; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; VALIDATE_PRODUCT = YES; }; name = Release; }; 187A8A011C8FC0A300D8DA51 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = "HYLabelDemo-Swift/Info.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.520it.HYLabelDemo-Swift"; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Debug; }; 187A8A021C8FC0A300D8DA51 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = "HYLabelDemo-Swift/Info.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.520it.HYLabelDemo-Swift"; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 187A89E91C8FC0A300D8DA51 /* Build configuration list for PBXProject "HYLabelDemo-Swift" */ = { isa = XCConfigurationList; buildConfigurations = ( 187A89FE1C8FC0A300D8DA51 /* Debug */, 187A89FF1C8FC0A300D8DA51 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 187A8A001C8FC0A300D8DA51 /* Build configuration list for PBXNativeTarget "HYLabelDemo-Swift" */ = { isa = XCConfigurationList; buildConfigurations = ( 187A8A011C8FC0A300D8DA51 /* Debug */, 187A8A021C8FC0A300D8DA51 /* Release */, ); defaultConfigurationIsVisible = 0; }; /* End XCConfigurationList section */ }; rootObject = 187A89E61C8FC0A300D8DA51 /* Project object */; } ================================================ FILE: HYLabelDemoOC/HYLabelDemoOC/AppDelegate.h ================================================ // // AppDelegate.h // HYLabelDemoOC // // Created by apple on 16/3/15. // Copyright © 2016年 xiaomage. All rights reserved. // #import @interface AppDelegate : UIResponder @property (strong, nonatomic) UIWindow *window; @end ================================================ FILE: HYLabelDemoOC/HYLabelDemoOC/AppDelegate.m ================================================ // // AppDelegate.m // HYLabelDemoOC // // Created by apple on 16/3/15. // Copyright © 2016年 xiaomage. All rights reserved. // #import "AppDelegate.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. return YES; } - (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } - (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - (void)applicationWillEnterForeground:(UIApplication *)application { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } - (void)applicationDidBecomeActive:(UIApplication *)application { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } @end ================================================ FILE: HYLabelDemoOC/HYLabelDemoOC/Assets.xcassets/AppIcon.appiconset/Contents.json ================================================ { "images" : [ { "idiom" : "iphone", "size" : "29x29", "scale" : "2x" }, { "idiom" : "iphone", "size" : "29x29", "scale" : "3x" }, { "idiom" : "iphone", "size" : "40x40", "scale" : "2x" }, { "idiom" : "iphone", "size" : "40x40", "scale" : "3x" }, { "idiom" : "iphone", "size" : "60x60", "scale" : "2x" }, { "idiom" : "iphone", "size" : "60x60", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: HYLabelDemoOC/HYLabelDemoOC/Base.lproj/LaunchScreen.storyboard ================================================ ================================================ FILE: HYLabelDemoOC/HYLabelDemoOC/Base.lproj/Main.storyboard ================================================ ================================================ FILE: HYLabelDemoOC/HYLabelDemoOC/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType APPL CFBundleShortVersionString 1.0 CFBundleSignature ???? CFBundleVersion 1 LSRequiresIPhoneOS UILaunchStoryboardName LaunchScreen UIMainStoryboardFile Main UIRequiredDeviceCapabilities armv7 UISupportedInterfaceOrientations UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight ================================================ FILE: HYLabelDemoOC/HYLabelDemoOC/Source/HYLabel.swift ================================================ // // HYLabel.swift // HYLabel // // Created by apple on 16/3/8. // Copyright © 2016年 xiaomage. All rights reserved. // import UIKit enum TapHandlerType : Int { case noneHandle = 0 case userHandle = 1 case topicHandle = 2 case linkHandle = 3 } public class HYLabel: UILabel { // MARK:- 属性 // 重写系统的属性 override public var text : String? { didSet { prepareText() } } override public var attributedText: NSAttributedString? { didSet { prepareText() } } override public var font: UIFont! { didSet { prepareText() } } override public var textColor: UIColor! { didSet { prepareText() } } // 懒加载属性 private lazy var textStorage : NSTextStorage = NSTextStorage() // NSMutableAttributeString的子类 private lazy var layoutManager : NSLayoutManager = NSLayoutManager() // 布局管理者 private lazy var textContainer : NSTextContainer = NSTextContainer() // 容器,需要设置容器的大小 // 用于记录下标值 private lazy var linkRanges : [NSRange] = [NSRange]() private lazy var userRanges : [NSRange] = [NSRange]() private lazy var topicRanges : [NSRange] = [NSRange]() // 用于记录用户选中的range private var selectedRange : NSRange? // 用户记录点击还是松开 private var isSelected : Bool = false // 闭包属性,用于回调 private var tapHandlerType : TapHandlerType = TapHandlerType.noneHandle public typealias HYTapHandler = (HYLabel, String, NSRange) -> Void public var linkTapHandler : HYTapHandler? public var topicTapHandler : HYTapHandler? public var userTapHandler : HYTapHandler? // MARK:- 构造函数 override init(frame: CGRect) { super.init(frame: frame) prepareTextSystem() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepareTextSystem() } // MARK:- 布局子控件 override public func layoutSubviews() { super.layoutSubviews() // 设置容器的大小为Label的尺寸 textContainer.size = frame.size } // MARK:- 重写drawTextInRect方法 override public func drawTextInRect(rect: CGRect) { // 1.绘制背景 if selectedRange != nil { // 2.0.确定颜色 let selectedColor = isSelected ? UIColor(white: 0.7, alpha: 0.2) : UIColor.clearColor() // 2.1.设置颜色 textStorage.addAttribute(NSBackgroundColorAttributeName, value: selectedColor, range: selectedRange!) // 2.2.绘制背景 layoutManager.drawBackgroundForGlyphRange(selectedRange!, atPoint: CGPoint(x: 0, y: 0)) } // 2.绘制字形 // 需要绘制的范围 let range = NSRange(location: 0, length: textStorage.length) layoutManager.drawGlyphsForGlyphRange(range, atPoint: CGPointZero) } } extension HYLabel { /// 准备文本系统 private func prepareTextSystem() { // 0.准备文本 prepareText() // 1.将布局添加到storeage中 textStorage.addLayoutManager(layoutManager) // 2.将容器添加到布局中 layoutManager.addTextContainer(textContainer) // 3.让label可以和用户交互 userInteractionEnabled = true // 4.设置间距为0 textContainer.lineFragmentPadding = 0 } /// 准备文本 private func prepareText() { // 1.准备字符串 var attrString : NSAttributedString? if attributedText != nil { attrString = attributedText } else if text != nil { attrString = NSAttributedString(string: text!) } else { attrString = NSAttributedString(string: "") } selectedRange = nil // 2.设置换行模型 let attrStringM = addLineBreak(attrString!) attrStringM.addAttribute(NSFontAttributeName, value: font, range: NSRange(location: 0, length: attrStringM.length)) // 3.设置textStorage的内容 textStorage.setAttributedString(attrStringM) // 4.匹配URL if let linkRanges = getLinkRanges() { self.linkRanges = linkRanges for range in linkRanges { textStorage.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: range) } } // 5.匹配@用户 if let userRanges = getRanges("@[\\u4e00-\\u9fa5a-zA-Z0-9_-]*") { self.userRanges = userRanges for range in userRanges { textStorage.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: range) } } // 6.匹配话题## if let topicRanges = getRanges("#.*?#") { self.topicRanges = topicRanges for range in topicRanges { textStorage.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: range) } } setNeedsDisplay() } } // MARK:- 字符串匹配封装 extension HYLabel { private func getRanges(pattern : String) -> [NSRange]? { // 创建正则表达式对象 guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else { return nil } return getRangesFromResult(regex) } private func getLinkRanges() -> [NSRange]? { // 创建正则表达式 guard let detector = try? NSDataDetector(types: NSTextCheckingType.Link.rawValue) else { return nil } return getRangesFromResult(detector) } private func getRangesFromResult(regex : NSRegularExpression) -> [NSRange] { // 1.匹配结果 let results = regex.matchesInString(textStorage.string, options: [], range: NSRange(location: 0, length: textStorage.length)) // 2.遍历结果 var ranges = [NSRange]() for res in results { ranges.append(res.range) } return ranges } } // MARK:- 点击交互的封装 extension HYLabel { override public func touchesBegan(touches: Set, withEvent event: UIEvent?) { // 0.记录点击 isSelected = true // 1.获取用户点击的点 let selectedPoint = touches.first!.locationInView(self) // 2.获取该点所在的字符串的range selectedRange = getSelectRange(selectedPoint) // 3.是否处理了事件 if selectedRange == nil { super.touchesBegan(touches, withEvent: event) } } override public func touchesEnded(touches: Set, withEvent event: UIEvent?) { if selectedRange == nil { super.touchesBegan(touches, withEvent: event) return } // 0.记录松开 isSelected = false // 2.重新绘制 setNeedsDisplay() // 3.取出内容 let contentText = (textStorage.string as NSString).substringWithRange(selectedRange!) // 3.回调 switch tapHandlerType { case .linkHandle: if linkTapHandler != nil { linkTapHandler!(self, contentText, selectedRange!) } case .topicHandle: if topicTapHandler != nil { topicTapHandler!(self, contentText, selectedRange!) } case .userHandle: if userTapHandler != nil { userTapHandler!(self, contentText, selectedRange!) } default: break } } private func getSelectRange(selectedPoint : CGPoint) -> NSRange? { // 0.如果属性字符串为nil,则不需要判断 if textStorage.length == 0 { return nil } // 1.获取选中点所在的下标值(index) let index = layoutManager.glyphIndexForPoint(selectedPoint, inTextContainer: textContainer) // 2.判断下标在什么内 // 2.1.判断是否是一个链接 for linkRange in linkRanges { if index > linkRange.location && index < linkRange.location + linkRange.length { setNeedsDisplay() tapHandlerType = .linkHandle return linkRange } } // 2.2.判断是否是一个@用户 for userRange in userRanges { if index > userRange.location && index < userRange.location + userRange.length { setNeedsDisplay() tapHandlerType = .userHandle return userRange } } // 2.3.判断是否是一个#话题# for topicRange in topicRanges { if index > topicRange.location && index < topicRange.location + topicRange.length { setNeedsDisplay() tapHandlerType = .topicHandle return topicRange } } return nil } } // MARK:- 补充 extension HYLabel { /// 如果用户没有设置lineBreak,则所有内容会绘制到同一行中,因此需要主动设置 private func addLineBreak(attrString: NSAttributedString) -> NSMutableAttributedString { let attrStringM = NSMutableAttributedString(attributedString: attrString) if attrStringM.length == 0 { return attrStringM } var range = NSRange(location: 0, length: 0) var attributes = attrStringM.attributesAtIndex(0, effectiveRange: &range) var paragraphStyle = attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle if paragraphStyle != nil { paragraphStyle!.lineBreakMode = NSLineBreakMode.ByWordWrapping } else { paragraphStyle = NSMutableParagraphStyle() paragraphStyle!.lineBreakMode = NSLineBreakMode.ByWordWrapping attributes[NSParagraphStyleAttributeName] = paragraphStyle attrStringM.setAttributes(attributes, range: range) } return attrStringM } } ================================================ FILE: HYLabelDemoOC/HYLabelDemoOC/ViewController.h ================================================ // // ViewController.h // HYLabelDemoOC // // Created by apple on 16/3/15. // Copyright © 2016年 xiaomage. All rights reserved. // #import @interface ViewController : UIViewController @end ================================================ FILE: HYLabelDemoOC/HYLabelDemoOC/ViewController.m ================================================ // // ViewController.m // HYLabelDemoOC // // Created by apple on 16/3/15. // Copyright © 2016年 xiaomage. All rights reserved. // #import "ViewController.h" #import "HYLabelDemoOC-Swift.h" @interface ViewController () @property (weak, nonatomic) IBOutlet HYLabel *demoLabel; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.demoLabel.userTapHandler = ^(HYLabel *label, NSString *user, NSRange range){ NSLog(@"%@", label); NSLog(@"%@", user); NSLog(@"%@", NSStringFromRange(range)); }; self.demoLabel.linkTapHandler = ^(HYLabel *label, NSString *link, NSRange range){ NSLog(@"%@", label); NSLog(@"%@", link); NSLog(@"%@", NSStringFromRange(range)); }; self.demoLabel.userTapHandler = ^(HYLabel *label, NSString *topic, NSRange range){ NSLog(@"%@", label); NSLog(@"%@", topic); NSLog(@"%@", NSStringFromRange(range)); }; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { self.demoLabel.text = @"作者:@coderwhy 话题:#Label字符串识别# 网址:http://www.520it.com"; } @end ================================================ FILE: HYLabelDemoOC/HYLabelDemoOC/main.m ================================================ // // main.m // HYLabelDemoOC // // Created by apple on 16/3/15. // Copyright © 2016年 xiaomage. All rights reserved. // #import #import "AppDelegate.h" int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } } ================================================ FILE: HYLabelDemoOC/HYLabelDemoOC.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ 18B0EE1F1C97B4F700BD3B93 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 18B0EE1E1C97B4F700BD3B93 /* main.m */; }; 18B0EE221C97B4F700BD3B93 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 18B0EE211C97B4F700BD3B93 /* AppDelegate.m */; }; 18B0EE251C97B4F700BD3B93 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 18B0EE241C97B4F700BD3B93 /* ViewController.m */; }; 18B0EE281C97B4F700BD3B93 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 18B0EE261C97B4F700BD3B93 /* Main.storyboard */; }; 18B0EE2A1C97B4F700BD3B93 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 18B0EE291C97B4F700BD3B93 /* Assets.xcassets */; }; 18B0EE2D1C97B4F700BD3B93 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 18B0EE2B1C97B4F700BD3B93 /* LaunchScreen.storyboard */; }; 18B0EE391C97B6C500BD3B93 /* HYLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18B0EE381C97B6C500BD3B93 /* HYLabel.swift */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ 18B0EE1A1C97B4F700BD3B93 /* HYLabelDemoOC.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = HYLabelDemoOC.app; sourceTree = BUILT_PRODUCTS_DIR; }; 18B0EE1E1C97B4F700BD3B93 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 18B0EE201C97B4F700BD3B93 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; 18B0EE211C97B4F700BD3B93 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; 18B0EE231C97B4F700BD3B93 /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; 18B0EE241C97B4F700BD3B93 /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = ""; }; 18B0EE271C97B4F700BD3B93 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 18B0EE291C97B4F700BD3B93 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 18B0EE2C1C97B4F700BD3B93 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 18B0EE2E1C97B4F700BD3B93 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 18B0EE381C97B6C500BD3B93 /* HYLabel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HYLabel.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 18B0EE171C97B4F700BD3B93 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 18B0EE111C97B4F700BD3B93 = { isa = PBXGroup; children = ( 18B0EE1C1C97B4F700BD3B93 /* HYLabelDemoOC */, 18B0EE1B1C97B4F700BD3B93 /* Products */, ); sourceTree = ""; }; 18B0EE1B1C97B4F700BD3B93 /* Products */ = { isa = PBXGroup; children = ( 18B0EE1A1C97B4F700BD3B93 /* HYLabelDemoOC.app */, ); name = Products; sourceTree = ""; }; 18B0EE1C1C97B4F700BD3B93 /* HYLabelDemoOC */ = { isa = PBXGroup; children = ( 18B0EE371C97B6C500BD3B93 /* Source */, 18B0EE201C97B4F700BD3B93 /* AppDelegate.h */, 18B0EE211C97B4F700BD3B93 /* AppDelegate.m */, 18B0EE231C97B4F700BD3B93 /* ViewController.h */, 18B0EE241C97B4F700BD3B93 /* ViewController.m */, 18B0EE261C97B4F700BD3B93 /* Main.storyboard */, 18B0EE291C97B4F700BD3B93 /* Assets.xcassets */, 18B0EE2B1C97B4F700BD3B93 /* LaunchScreen.storyboard */, 18B0EE2E1C97B4F700BD3B93 /* Info.plist */, 18B0EE1D1C97B4F700BD3B93 /* Supporting Files */, ); path = HYLabelDemoOC; sourceTree = ""; }; 18B0EE1D1C97B4F700BD3B93 /* Supporting Files */ = { isa = PBXGroup; children = ( 18B0EE1E1C97B4F700BD3B93 /* main.m */, ); name = "Supporting Files"; sourceTree = ""; }; 18B0EE371C97B6C500BD3B93 /* Source */ = { isa = PBXGroup; children = ( 18B0EE381C97B6C500BD3B93 /* HYLabel.swift */, ); path = Source; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 18B0EE191C97B4F700BD3B93 /* HYLabelDemoOC */ = { isa = PBXNativeTarget; buildConfigurationList = 18B0EE311C97B4F700BD3B93 /* Build configuration list for PBXNativeTarget "HYLabelDemoOC" */; buildPhases = ( 18B0EE161C97B4F700BD3B93 /* Sources */, 18B0EE171C97B4F700BD3B93 /* Frameworks */, 18B0EE181C97B4F700BD3B93 /* Resources */, ); buildRules = ( ); dependencies = ( ); name = HYLabelDemoOC; productName = HYLabelDemoOC; productReference = 18B0EE1A1C97B4F700BD3B93 /* HYLabelDemoOC.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 18B0EE121C97B4F700BD3B93 /* Project object */ = { isa = PBXProject; attributes = { LastUpgradeCheck = 0720; ORGANIZATIONNAME = xiaomage; TargetAttributes = { 18B0EE191C97B4F700BD3B93 = { CreatedOnToolsVersion = 7.2; }; }; }; buildConfigurationList = 18B0EE151C97B4F700BD3B93 /* Build configuration list for PBXProject "HYLabelDemoOC" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = 18B0EE111C97B4F700BD3B93; productRefGroup = 18B0EE1B1C97B4F700BD3B93 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 18B0EE191C97B4F700BD3B93 /* HYLabelDemoOC */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 18B0EE181C97B4F700BD3B93 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 18B0EE2D1C97B4F700BD3B93 /* LaunchScreen.storyboard in Resources */, 18B0EE2A1C97B4F700BD3B93 /* Assets.xcassets in Resources */, 18B0EE281C97B4F700BD3B93 /* Main.storyboard in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 18B0EE161C97B4F700BD3B93 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 18B0EE251C97B4F700BD3B93 /* ViewController.m in Sources */, 18B0EE391C97B6C500BD3B93 /* HYLabel.swift in Sources */, 18B0EE221C97B4F700BD3B93 /* AppDelegate.m in Sources */, 18B0EE1F1C97B4F700BD3B93 /* main.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXVariantGroup section */ 18B0EE261C97B4F700BD3B93 /* Main.storyboard */ = { isa = PBXVariantGroup; children = ( 18B0EE271C97B4F700BD3B93 /* Base */, ); name = Main.storyboard; sourceTree = ""; }; 18B0EE2B1C97B4F700BD3B93 /* LaunchScreen.storyboard */ = { isa = PBXVariantGroup; children = ( 18B0EE2C1C97B4F700BD3B93 /* Base */, ); name = LaunchScreen.storyboard; sourceTree = ""; }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ 18B0EE2F1C97B4F700BD3B93 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 9.2; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; }; name = Debug; }; 18B0EE301C97B4F700BD3B93 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 9.2; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; VALIDATE_PRODUCT = YES; }; name = Release; }; 18B0EE321C97B4F700BD3B93 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = HYLabelDemoOC/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.520it.HYLabelDemoOC; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Debug; }; 18B0EE331C97B4F700BD3B93 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = HYLabelDemoOC/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.520it.HYLabelDemoOC; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 18B0EE151C97B4F700BD3B93 /* Build configuration list for PBXProject "HYLabelDemoOC" */ = { isa = XCConfigurationList; buildConfigurations = ( 18B0EE2F1C97B4F700BD3B93 /* Debug */, 18B0EE301C97B4F700BD3B93 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 18B0EE311C97B4F700BD3B93 /* Build configuration list for PBXNativeTarget "HYLabelDemoOC" */ = { isa = XCConfigurationList; buildConfigurations = ( 18B0EE321C97B4F700BD3B93 /* Debug */, 18B0EE331C97B4F700BD3B93 /* Release */, ); defaultConfigurationIsVisible = 0; }; /* End XCConfigurationList section */ }; rootObject = 18B0EE121C97B4F700BD3B93 /* Project object */; } ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2016 coderwhy 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. ================================================ FILE: README.md ================================================ # HYLabel ### 框架的作用 * 用于识别Label中的@用户-话题##-链接 * 框架地址:[https://github.com/coderwhy/HYLabel](https://github.com/coderwhy/HYLabel) ### 使用效果 * 如图所示 * 并且可以监听点击
* ![image](https://raw.githubusercontent.com/coderwhy/HYLabel/master/ReadmeImage/image1.png) ### 使用方式 * 导入框架 * 直接将HYLabel.swift拖入项目 * 该框架支持cocoapods:pod 'HYLabel', '~> 1.0.1' * 将UIlabel修改为HYLabel * 按照下列方式监听点击即可 * OC监听方式 ```objc self.demoLabel.userTapHandler = ^(HYLabel *label, NSString *user, NSRange range){ NSLog(@"%@", label); NSLog(@"%@", user); NSLog(@"%@", NSStringFromRange(range)); }; self.demoLabel.linkTapHandler = ^(HYLabel *label, NSString *link, NSRange range){ NSLog(@"%@", label); NSLog(@"%@", link); NSLog(@"%@", NSStringFromRange(range)); }; self.demoLabel.userTapHandler = ^(HYLabel *label, NSString *topic, NSRange range){ NSLog(@"%@", label); NSLog(@"%@", topic); NSLog(@"%@", NSStringFromRange(range)); }; ``` * swift监听方式 ```swift // 监听@谁谁谁的点击 demoLabel.userTapHandler = { (label, user, range) in print(label) print(user) print(range) } // 监听链接的点击 demoLabel.linkTapHandler = { (label, link, range) in print(label) print(link) print(range) } // 监听话题的点击 demoLabel.topicTapHandler = { (label, topic, range) in print(label) print(topic) print(range) } ```