├── .gitignore ├── 1.png ├── README.md ├── RichTextView.podspec ├── RichTextView.xcodeproj ├── project.pbxproj ├── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcshareddata │ │ ├── IDEWorkspaceChecks.plist │ │ └── RichTextView.xccheckout └── xcuserdata │ └── kevin.xcuserdatad │ ├── xcdebugger │ └── Breakpoints_v2.xcbkptlist │ └── xcschemes │ ├── RichTextView.xcscheme │ └── xcschememanagement.plist ├── RichTextView ├── AppDelegate.swift ├── Base.lproj │ ├── LaunchScreen.xib │ └── Main.storyboard ├── Images.xcassets │ ├── AppIcon.appiconset │ │ └── Contents.json │ └── WatchBlack.imageset │ │ ├── Contents.json │ │ └── Watch Black.png ├── Info.plist ├── Source │ ├── RichTextStorage.swift │ ├── RichTextView.swift │ └── RichTextViewDelegateHandler.swift └── ViewController.swift └── RichTextViewTests ├── Info.plist └── RichTextViewTests.swift /.gitignore: -------------------------------------------------------------------------------- 1 | Build 2 | RichTextView.xcodeproj/project.xcworkspace/xcuserdata/kevin.xcuserdatad/UserInterfaceState.xcuserstate 3 | .DS_Store 4 | xcuserdata 5 | zhowkevin.xcuserdatad 6 | -------------------------------------------------------------------------------- /1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kevinzhow/RichTextView/3606de2e722a1dd892094ee689cb53b033fc553c/1.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RichTextView 2 | 3 | Rich TextView Solution based on TextKit 4 | 5 | Features 6 | 7 | - Mention 8 | - HashTag 9 | - URL 10 | - Email 11 | - Image 12 | - Custom 13 | - Interaction Delegate 14 | 15 | Also support custom text style with AttributeText. 16 | 17 | ![1](1.png) 18 | -------------------------------------------------------------------------------- /RichTextView.podspec: -------------------------------------------------------------------------------- 1 | Pod::Spec.new do |s| 2 | 3 | s.name = "RichTextView" 4 | s.version = "0.3.1" 5 | s.summary = "RichTextView based On TextKit" 6 | 7 | s.description = <<-DESC 8 | RichTextView based On TextKit, With Mention, Hashtag Feature 9 | DESC 10 | 11 | s.homepage = "https://github.com/kevinzhow/RichTextView" 12 | s.screenshots = "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/logo.png" 13 | 14 | s.license = { :type => "MIT", :file => "LICENSE" } 15 | 16 | s.authors = { "kevinzhow" => "kevinchou.c@gmail.com" } 17 | s.social_media_url = "http://twitter.com/kevinzhow" 18 | 19 | s.ios.deployment_target = "8.0" 20 | # s.osx.deployment_target = "10.7" 21 | 22 | s.source = { :git => "https://github.com/kevinzhow/RichTextView.git", :tag => s.version } 23 | s.source_files = "RichTextView/Source/*.swift" 24 | s.requires_arc = true 25 | 26 | end 27 | -------------------------------------------------------------------------------- /RichTextView.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | 0AE1539A1B4D606B00B186FF /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AE153991B4D606B00B186FF /* AppDelegate.swift */; }; 11 | 0AE1539C1B4D606B00B186FF /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AE1539B1B4D606B00B186FF /* ViewController.swift */; }; 12 | 0AE1539F1B4D606B00B186FF /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 0AE1539D1B4D606B00B186FF /* Main.storyboard */; }; 13 | 0AE153A11B4D606B00B186FF /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 0AE153A01B4D606B00B186FF /* Images.xcassets */; }; 14 | 0AE153A41B4D606B00B186FF /* LaunchScreen.xib in Resources */ = {isa = PBXBuildFile; fileRef = 0AE153A21B4D606B00B186FF /* LaunchScreen.xib */; }; 15 | 0AE153B01B4D606B00B186FF /* RichTextViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AE153AF1B4D606B00B186FF /* RichTextViewTests.swift */; }; 16 | 0AE153BA1B4D7E9E00B186FF /* RichTextView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AE153B91B4D7E9E00B186FF /* RichTextView.swift */; }; 17 | 0AE153BD1B4D80CC00B186FF /* RichTextStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AE153BC1B4D80CC00B186FF /* RichTextStorage.swift */; }; 18 | 0AE153C11B4D96AF00B186FF /* RichTextViewDelegateHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AE153C01B4D96AF00B186FF /* RichTextViewDelegateHandler.swift */; }; 19 | /* End PBXBuildFile section */ 20 | 21 | /* Begin PBXContainerItemProxy section */ 22 | 0AE153AA1B4D606B00B186FF /* PBXContainerItemProxy */ = { 23 | isa = PBXContainerItemProxy; 24 | containerPortal = 0AE1538C1B4D606B00B186FF /* Project object */; 25 | proxyType = 1; 26 | remoteGlobalIDString = 0AE153931B4D606B00B186FF; 27 | remoteInfo = RichTextView; 28 | }; 29 | /* End PBXContainerItemProxy section */ 30 | 31 | /* Begin PBXFileReference section */ 32 | 0AE153941B4D606B00B186FF /* RichTextView.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = RichTextView.app; sourceTree = BUILT_PRODUCTS_DIR; }; 33 | 0AE153981B4D606B00B186FF /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 34 | 0AE153991B4D606B00B186FF /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 35 | 0AE1539B1B4D606B00B186FF /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; 36 | 0AE1539E1B4D606B00B186FF /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 37 | 0AE153A01B4D606B00B186FF /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = ""; }; 38 | 0AE153A31B4D606B00B186FF /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/LaunchScreen.xib; sourceTree = ""; }; 39 | 0AE153A91B4D606B00B186FF /* RichTextViewTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RichTextViewTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 40 | 0AE153AE1B4D606B00B186FF /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 41 | 0AE153AF1B4D606B00B186FF /* RichTextViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RichTextViewTests.swift; sourceTree = ""; }; 42 | 0AE153B91B4D7E9E00B186FF /* RichTextView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = RichTextView.swift; path = Source/RichTextView.swift; sourceTree = ""; }; 43 | 0AE153BC1B4D80CC00B186FF /* RichTextStorage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = RichTextStorage.swift; path = Source/RichTextStorage.swift; sourceTree = ""; }; 44 | 0AE153C01B4D96AF00B186FF /* RichTextViewDelegateHandler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = RichTextViewDelegateHandler.swift; path = Source/RichTextViewDelegateHandler.swift; sourceTree = ""; }; 45 | /* End PBXFileReference section */ 46 | 47 | /* Begin PBXFrameworksBuildPhase section */ 48 | 0AE153911B4D606B00B186FF /* Frameworks */ = { 49 | isa = PBXFrameworksBuildPhase; 50 | buildActionMask = 2147483647; 51 | files = ( 52 | ); 53 | runOnlyForDeploymentPostprocessing = 0; 54 | }; 55 | 0AE153A61B4D606B00B186FF /* Frameworks */ = { 56 | isa = PBXFrameworksBuildPhase; 57 | buildActionMask = 2147483647; 58 | files = ( 59 | ); 60 | runOnlyForDeploymentPostprocessing = 0; 61 | }; 62 | /* End PBXFrameworksBuildPhase section */ 63 | 64 | /* Begin PBXGroup section */ 65 | 0AE1538B1B4D606B00B186FF = { 66 | isa = PBXGroup; 67 | children = ( 68 | 0AE153961B4D606B00B186FF /* RichTextView */, 69 | 0AE153AC1B4D606B00B186FF /* RichTextViewTests */, 70 | 0AE153951B4D606B00B186FF /* Products */, 71 | ); 72 | sourceTree = ""; 73 | }; 74 | 0AE153951B4D606B00B186FF /* Products */ = { 75 | isa = PBXGroup; 76 | children = ( 77 | 0AE153941B4D606B00B186FF /* RichTextView.app */, 78 | 0AE153A91B4D606B00B186FF /* RichTextViewTests.xctest */, 79 | ); 80 | name = Products; 81 | sourceTree = ""; 82 | }; 83 | 0AE153961B4D606B00B186FF /* RichTextView */ = { 84 | isa = PBXGroup; 85 | children = ( 86 | 0AE153BB1B4D7EA400B186FF /* Source */, 87 | 0AE153991B4D606B00B186FF /* AppDelegate.swift */, 88 | 0AE1539B1B4D606B00B186FF /* ViewController.swift */, 89 | 0AE1539D1B4D606B00B186FF /* Main.storyboard */, 90 | 0AE153A01B4D606B00B186FF /* Images.xcassets */, 91 | 0AE153A21B4D606B00B186FF /* LaunchScreen.xib */, 92 | 0AE153971B4D606B00B186FF /* Supporting Files */, 93 | ); 94 | path = RichTextView; 95 | sourceTree = ""; 96 | }; 97 | 0AE153971B4D606B00B186FF /* Supporting Files */ = { 98 | isa = PBXGroup; 99 | children = ( 100 | 0AE153981B4D606B00B186FF /* Info.plist */, 101 | ); 102 | name = "Supporting Files"; 103 | sourceTree = ""; 104 | }; 105 | 0AE153AC1B4D606B00B186FF /* RichTextViewTests */ = { 106 | isa = PBXGroup; 107 | children = ( 108 | 0AE153AF1B4D606B00B186FF /* RichTextViewTests.swift */, 109 | 0AE153AD1B4D606B00B186FF /* Supporting Files */, 110 | ); 111 | path = RichTextViewTests; 112 | sourceTree = ""; 113 | }; 114 | 0AE153AD1B4D606B00B186FF /* Supporting Files */ = { 115 | isa = PBXGroup; 116 | children = ( 117 | 0AE153AE1B4D606B00B186FF /* Info.plist */, 118 | ); 119 | name = "Supporting Files"; 120 | sourceTree = ""; 121 | }; 122 | 0AE153BB1B4D7EA400B186FF /* Source */ = { 123 | isa = PBXGroup; 124 | children = ( 125 | 0AE153C01B4D96AF00B186FF /* RichTextViewDelegateHandler.swift */, 126 | 0AE153BC1B4D80CC00B186FF /* RichTextStorage.swift */, 127 | 0AE153B91B4D7E9E00B186FF /* RichTextView.swift */, 128 | ); 129 | name = Source; 130 | sourceTree = ""; 131 | }; 132 | /* End PBXGroup section */ 133 | 134 | /* Begin PBXNativeTarget section */ 135 | 0AE153931B4D606B00B186FF /* RichTextView */ = { 136 | isa = PBXNativeTarget; 137 | buildConfigurationList = 0AE153B31B4D606B00B186FF /* Build configuration list for PBXNativeTarget "RichTextView" */; 138 | buildPhases = ( 139 | 0AE153901B4D606B00B186FF /* Sources */, 140 | 0AE153911B4D606B00B186FF /* Frameworks */, 141 | 0AE153921B4D606B00B186FF /* Resources */, 142 | ); 143 | buildRules = ( 144 | ); 145 | dependencies = ( 146 | ); 147 | name = RichTextView; 148 | productName = RichTextView; 149 | productReference = 0AE153941B4D606B00B186FF /* RichTextView.app */; 150 | productType = "com.apple.product-type.application"; 151 | }; 152 | 0AE153A81B4D606B00B186FF /* RichTextViewTests */ = { 153 | isa = PBXNativeTarget; 154 | buildConfigurationList = 0AE153B61B4D606B00B186FF /* Build configuration list for PBXNativeTarget "RichTextViewTests" */; 155 | buildPhases = ( 156 | 0AE153A51B4D606B00B186FF /* Sources */, 157 | 0AE153A61B4D606B00B186FF /* Frameworks */, 158 | 0AE153A71B4D606B00B186FF /* Resources */, 159 | ); 160 | buildRules = ( 161 | ); 162 | dependencies = ( 163 | 0AE153AB1B4D606B00B186FF /* PBXTargetDependency */, 164 | ); 165 | name = RichTextViewTests; 166 | productName = RichTextViewTests; 167 | productReference = 0AE153A91B4D606B00B186FF /* RichTextViewTests.xctest */; 168 | productType = "com.apple.product-type.bundle.unit-test"; 169 | }; 170 | /* End PBXNativeTarget section */ 171 | 172 | /* Begin PBXProject section */ 173 | 0AE1538C1B4D606B00B186FF /* Project object */ = { 174 | isa = PBXProject; 175 | attributes = { 176 | LastSwiftMigration = 0700; 177 | LastSwiftUpdateCheck = 0700; 178 | LastUpgradeCheck = 1010; 179 | ORGANIZATIONNAME = kevinzhow; 180 | TargetAttributes = { 181 | 0AE153931B4D606B00B186FF = { 182 | CreatedOnToolsVersion = 6.4; 183 | }; 184 | 0AE153A81B4D606B00B186FF = { 185 | CreatedOnToolsVersion = 6.4; 186 | TestTargetID = 0AE153931B4D606B00B186FF; 187 | }; 188 | }; 189 | }; 190 | buildConfigurationList = 0AE1538F1B4D606B00B186FF /* Build configuration list for PBXProject "RichTextView" */; 191 | compatibilityVersion = "Xcode 3.2"; 192 | developmentRegion = English; 193 | hasScannedForEncodings = 0; 194 | knownRegions = ( 195 | en, 196 | Base, 197 | ); 198 | mainGroup = 0AE1538B1B4D606B00B186FF; 199 | productRefGroup = 0AE153951B4D606B00B186FF /* Products */; 200 | projectDirPath = ""; 201 | projectRoot = ""; 202 | targets = ( 203 | 0AE153931B4D606B00B186FF /* RichTextView */, 204 | 0AE153A81B4D606B00B186FF /* RichTextViewTests */, 205 | ); 206 | }; 207 | /* End PBXProject section */ 208 | 209 | /* Begin PBXResourcesBuildPhase section */ 210 | 0AE153921B4D606B00B186FF /* Resources */ = { 211 | isa = PBXResourcesBuildPhase; 212 | buildActionMask = 2147483647; 213 | files = ( 214 | 0AE1539F1B4D606B00B186FF /* Main.storyboard in Resources */, 215 | 0AE153A41B4D606B00B186FF /* LaunchScreen.xib in Resources */, 216 | 0AE153A11B4D606B00B186FF /* Images.xcassets in Resources */, 217 | ); 218 | runOnlyForDeploymentPostprocessing = 0; 219 | }; 220 | 0AE153A71B4D606B00B186FF /* Resources */ = { 221 | isa = PBXResourcesBuildPhase; 222 | buildActionMask = 2147483647; 223 | files = ( 224 | ); 225 | runOnlyForDeploymentPostprocessing = 0; 226 | }; 227 | /* End PBXResourcesBuildPhase section */ 228 | 229 | /* Begin PBXSourcesBuildPhase section */ 230 | 0AE153901B4D606B00B186FF /* Sources */ = { 231 | isa = PBXSourcesBuildPhase; 232 | buildActionMask = 2147483647; 233 | files = ( 234 | 0AE153BD1B4D80CC00B186FF /* RichTextStorage.swift in Sources */, 235 | 0AE1539C1B4D606B00B186FF /* ViewController.swift in Sources */, 236 | 0AE1539A1B4D606B00B186FF /* AppDelegate.swift in Sources */, 237 | 0AE153BA1B4D7E9E00B186FF /* RichTextView.swift in Sources */, 238 | 0AE153C11B4D96AF00B186FF /* RichTextViewDelegateHandler.swift in Sources */, 239 | ); 240 | runOnlyForDeploymentPostprocessing = 0; 241 | }; 242 | 0AE153A51B4D606B00B186FF /* Sources */ = { 243 | isa = PBXSourcesBuildPhase; 244 | buildActionMask = 2147483647; 245 | files = ( 246 | 0AE153B01B4D606B00B186FF /* RichTextViewTests.swift in Sources */, 247 | ); 248 | runOnlyForDeploymentPostprocessing = 0; 249 | }; 250 | /* End PBXSourcesBuildPhase section */ 251 | 252 | /* Begin PBXTargetDependency section */ 253 | 0AE153AB1B4D606B00B186FF /* PBXTargetDependency */ = { 254 | isa = PBXTargetDependency; 255 | target = 0AE153931B4D606B00B186FF /* RichTextView */; 256 | targetProxy = 0AE153AA1B4D606B00B186FF /* PBXContainerItemProxy */; 257 | }; 258 | /* End PBXTargetDependency section */ 259 | 260 | /* Begin PBXVariantGroup section */ 261 | 0AE1539D1B4D606B00B186FF /* Main.storyboard */ = { 262 | isa = PBXVariantGroup; 263 | children = ( 264 | 0AE1539E1B4D606B00B186FF /* Base */, 265 | ); 266 | name = Main.storyboard; 267 | sourceTree = ""; 268 | }; 269 | 0AE153A21B4D606B00B186FF /* LaunchScreen.xib */ = { 270 | isa = PBXVariantGroup; 271 | children = ( 272 | 0AE153A31B4D606B00B186FF /* Base */, 273 | ); 274 | name = LaunchScreen.xib; 275 | sourceTree = ""; 276 | }; 277 | /* End PBXVariantGroup section */ 278 | 279 | /* Begin XCBuildConfiguration section */ 280 | 0AE153B11B4D606B00B186FF /* Debug */ = { 281 | isa = XCBuildConfiguration; 282 | buildSettings = { 283 | ALWAYS_SEARCH_USER_PATHS = NO; 284 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 285 | CLANG_CXX_LIBRARY = "libc++"; 286 | CLANG_ENABLE_MODULES = YES; 287 | CLANG_ENABLE_OBJC_ARC = YES; 288 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 289 | CLANG_WARN_BOOL_CONVERSION = YES; 290 | CLANG_WARN_COMMA = YES; 291 | CLANG_WARN_CONSTANT_CONVERSION = YES; 292 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 293 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 294 | CLANG_WARN_EMPTY_BODY = YES; 295 | CLANG_WARN_ENUM_CONVERSION = YES; 296 | CLANG_WARN_INFINITE_RECURSION = YES; 297 | CLANG_WARN_INT_CONVERSION = YES; 298 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 299 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 300 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 301 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 302 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 303 | CLANG_WARN_STRICT_PROTOTYPES = YES; 304 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 305 | CLANG_WARN_UNREACHABLE_CODE = YES; 306 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 307 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 308 | COPY_PHASE_STRIP = NO; 309 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 310 | ENABLE_STRICT_OBJC_MSGSEND = YES; 311 | ENABLE_TESTABILITY = YES; 312 | GCC_C_LANGUAGE_STANDARD = gnu99; 313 | GCC_DYNAMIC_NO_PIC = NO; 314 | GCC_NO_COMMON_BLOCKS = YES; 315 | GCC_OPTIMIZATION_LEVEL = 0; 316 | GCC_PREPROCESSOR_DEFINITIONS = ( 317 | "DEBUG=1", 318 | "$(inherited)", 319 | ); 320 | GCC_SYMBOLS_PRIVATE_EXTERN = NO; 321 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 322 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 323 | GCC_WARN_UNDECLARED_SELECTOR = YES; 324 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 325 | GCC_WARN_UNUSED_FUNCTION = YES; 326 | GCC_WARN_UNUSED_VARIABLE = YES; 327 | IPHONEOS_DEPLOYMENT_TARGET = 8.4; 328 | MTL_ENABLE_DEBUG_INFO = YES; 329 | ONLY_ACTIVE_ARCH = YES; 330 | SDKROOT = iphoneos; 331 | SWIFT_OPTIMIZATION_LEVEL = "-Onone"; 332 | }; 333 | name = Debug; 334 | }; 335 | 0AE153B21B4D606B00B186FF /* Release */ = { 336 | isa = XCBuildConfiguration; 337 | buildSettings = { 338 | ALWAYS_SEARCH_USER_PATHS = NO; 339 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 340 | CLANG_CXX_LIBRARY = "libc++"; 341 | CLANG_ENABLE_MODULES = YES; 342 | CLANG_ENABLE_OBJC_ARC = YES; 343 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 344 | CLANG_WARN_BOOL_CONVERSION = YES; 345 | CLANG_WARN_COMMA = YES; 346 | CLANG_WARN_CONSTANT_CONVERSION = YES; 347 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 348 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 349 | CLANG_WARN_EMPTY_BODY = YES; 350 | CLANG_WARN_ENUM_CONVERSION = YES; 351 | CLANG_WARN_INFINITE_RECURSION = YES; 352 | CLANG_WARN_INT_CONVERSION = YES; 353 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 354 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 355 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 356 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 357 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 358 | CLANG_WARN_STRICT_PROTOTYPES = YES; 359 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 360 | CLANG_WARN_UNREACHABLE_CODE = YES; 361 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 362 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 363 | COPY_PHASE_STRIP = NO; 364 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 365 | ENABLE_NS_ASSERTIONS = NO; 366 | ENABLE_STRICT_OBJC_MSGSEND = YES; 367 | GCC_C_LANGUAGE_STANDARD = gnu99; 368 | GCC_NO_COMMON_BLOCKS = YES; 369 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 370 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 371 | GCC_WARN_UNDECLARED_SELECTOR = YES; 372 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 373 | GCC_WARN_UNUSED_FUNCTION = YES; 374 | GCC_WARN_UNUSED_VARIABLE = YES; 375 | IPHONEOS_DEPLOYMENT_TARGET = 8.4; 376 | MTL_ENABLE_DEBUG_INFO = NO; 377 | SDKROOT = iphoneos; 378 | SWIFT_COMPILATION_MODE = wholemodule; 379 | VALIDATE_PRODUCT = YES; 380 | }; 381 | name = Release; 382 | }; 383 | 0AE153B41B4D606B00B186FF /* Debug */ = { 384 | isa = XCBuildConfiguration; 385 | buildSettings = { 386 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 387 | INFOPLIST_FILE = RichTextView/Info.plist; 388 | IPHONEOS_DEPLOYMENT_TARGET = 10.0; 389 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; 390 | PRODUCT_BUNDLE_IDENTIFIER = "kevinzhow.$(PRODUCT_NAME:rfc1034identifier)"; 391 | PRODUCT_NAME = "$(TARGET_NAME)"; 392 | SWIFT_VERSION = 4.2; 393 | }; 394 | name = Debug; 395 | }; 396 | 0AE153B51B4D606B00B186FF /* Release */ = { 397 | isa = XCBuildConfiguration; 398 | buildSettings = { 399 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 400 | INFOPLIST_FILE = RichTextView/Info.plist; 401 | IPHONEOS_DEPLOYMENT_TARGET = 10.0; 402 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; 403 | PRODUCT_BUNDLE_IDENTIFIER = "kevinzhow.$(PRODUCT_NAME:rfc1034identifier)"; 404 | PRODUCT_NAME = "$(TARGET_NAME)"; 405 | SWIFT_VERSION = 4.2; 406 | }; 407 | name = Release; 408 | }; 409 | 0AE153B71B4D606B00B186FF /* Debug */ = { 410 | isa = XCBuildConfiguration; 411 | buildSettings = { 412 | BUNDLE_LOADER = "$(TEST_HOST)"; 413 | FRAMEWORK_SEARCH_PATHS = ( 414 | "$(SDKROOT)/Developer/Library/Frameworks", 415 | "$(inherited)", 416 | ); 417 | GCC_PREPROCESSOR_DEFINITIONS = ( 418 | "DEBUG=1", 419 | "$(inherited)", 420 | ); 421 | INFOPLIST_FILE = RichTextViewTests/Info.plist; 422 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; 423 | PRODUCT_BUNDLE_IDENTIFIER = "kevinzhow.$(PRODUCT_NAME:rfc1034identifier)"; 424 | PRODUCT_NAME = "$(TARGET_NAME)"; 425 | TEST_HOST = "$(BUILT_PRODUCTS_DIR)/RichTextView.app/RichTextView"; 426 | }; 427 | name = Debug; 428 | }; 429 | 0AE153B81B4D606B00B186FF /* Release */ = { 430 | isa = XCBuildConfiguration; 431 | buildSettings = { 432 | BUNDLE_LOADER = "$(TEST_HOST)"; 433 | FRAMEWORK_SEARCH_PATHS = ( 434 | "$(SDKROOT)/Developer/Library/Frameworks", 435 | "$(inherited)", 436 | ); 437 | INFOPLIST_FILE = RichTextViewTests/Info.plist; 438 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; 439 | PRODUCT_BUNDLE_IDENTIFIER = "kevinzhow.$(PRODUCT_NAME:rfc1034identifier)"; 440 | PRODUCT_NAME = "$(TARGET_NAME)"; 441 | TEST_HOST = "$(BUILT_PRODUCTS_DIR)/RichTextView.app/RichTextView"; 442 | }; 443 | name = Release; 444 | }; 445 | /* End XCBuildConfiguration section */ 446 | 447 | /* Begin XCConfigurationList section */ 448 | 0AE1538F1B4D606B00B186FF /* Build configuration list for PBXProject "RichTextView" */ = { 449 | isa = XCConfigurationList; 450 | buildConfigurations = ( 451 | 0AE153B11B4D606B00B186FF /* Debug */, 452 | 0AE153B21B4D606B00B186FF /* Release */, 453 | ); 454 | defaultConfigurationIsVisible = 0; 455 | defaultConfigurationName = Release; 456 | }; 457 | 0AE153B31B4D606B00B186FF /* Build configuration list for PBXNativeTarget "RichTextView" */ = { 458 | isa = XCConfigurationList; 459 | buildConfigurations = ( 460 | 0AE153B41B4D606B00B186FF /* Debug */, 461 | 0AE153B51B4D606B00B186FF /* Release */, 462 | ); 463 | defaultConfigurationIsVisible = 0; 464 | defaultConfigurationName = Release; 465 | }; 466 | 0AE153B61B4D606B00B186FF /* Build configuration list for PBXNativeTarget "RichTextViewTests" */ = { 467 | isa = XCConfigurationList; 468 | buildConfigurations = ( 469 | 0AE153B71B4D606B00B186FF /* Debug */, 470 | 0AE153B81B4D606B00B186FF /* Release */, 471 | ); 472 | defaultConfigurationIsVisible = 0; 473 | defaultConfigurationName = Release; 474 | }; 475 | /* End XCConfigurationList section */ 476 | }; 477 | rootObject = 0AE1538C1B4D606B00B186FF /* Project object */; 478 | } 479 | -------------------------------------------------------------------------------- /RichTextView.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /RichTextView.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /RichTextView.xcodeproj/project.xcworkspace/xcshareddata/RichTextView.xccheckout: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDESourceControlProjectFavoriteDictionaryKey 6 | 7 | IDESourceControlProjectIdentifier 8 | 7469D5FF-09D3-4E15-BE9A-396C716CC1E1 9 | IDESourceControlProjectName 10 | RichTextView 11 | IDESourceControlProjectOriginsDictionary 12 | 13 | EF2885DCF93A7C651E75F07B38C23C5ADF0ACCFB 14 | github.com:kevinzhow/RichTextView.git 15 | 16 | IDESourceControlProjectPath 17 | RichTextView.xcodeproj 18 | IDESourceControlProjectRelativeInstallPathDictionary 19 | 20 | EF2885DCF93A7C651E75F07B38C23C5ADF0ACCFB 21 | ../.. 22 | 23 | IDESourceControlProjectURL 24 | github.com:kevinzhow/RichTextView.git 25 | IDESourceControlProjectVersion 26 | 111 27 | IDESourceControlProjectWCCIdentifier 28 | EF2885DCF93A7C651E75F07B38C23C5ADF0ACCFB 29 | IDESourceControlProjectWCConfigurations 30 | 31 | 32 | IDESourceControlRepositoryExtensionIdentifierKey 33 | public.vcs.git 34 | IDESourceControlWCCIdentifierKey 35 | EF2885DCF93A7C651E75F07B38C23C5ADF0ACCFB 36 | IDESourceControlWCCName 37 | RichTextView 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /RichTextView.xcodeproj/xcuserdata/kevin.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /RichTextView.xcodeproj/xcuserdata/kevin.xcuserdatad/xcschemes/RichTextView.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 29 | 35 | 36 | 37 | 38 | 39 | 44 | 45 | 47 | 53 | 54 | 55 | 56 | 57 | 63 | 64 | 65 | 66 | 75 | 77 | 83 | 84 | 85 | 86 | 87 | 88 | 94 | 96 | 102 | 103 | 104 | 105 | 107 | 108 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /RichTextView.xcodeproj/xcuserdata/kevin.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | RichTextView.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 0AE153931B4D606B00B186FF 16 | 17 | primary 18 | 19 | 20 | 0AE153A81B4D606B00B186FF 21 | 22 | primary 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /RichTextView/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.swift 3 | // RichTextView 4 | // 5 | // Created by kevinzhow on 15/7/8. 6 | // Copyright (c) 2015年 kevinzhow. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | 11 | @UIApplicationMain 12 | class AppDelegate: UIResponder, UIApplicationDelegate { 13 | 14 | var window: UIWindow? 15 | 16 | 17 | private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 18 | // Override point for customization after application launch. 19 | return true 20 | } 21 | 22 | func applicationWillResignActive(_ application: UIApplication) { 23 | // 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. 24 | // 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. 25 | } 26 | 27 | func applicationDidEnterBackground(_ application: UIApplication) { 28 | // 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. 29 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 30 | } 31 | 32 | func applicationWillEnterForeground(_ application: UIApplication) { 33 | // 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. 34 | } 35 | 36 | func applicationDidBecomeActive(_ application: UIApplication) { 37 | // 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. 38 | } 39 | 40 | func applicationWillTerminate(_ application: UIApplication) { 41 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 42 | } 43 | 44 | 45 | } 46 | 47 | -------------------------------------------------------------------------------- /RichTextView/Base.lproj/LaunchScreen.xib: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 25 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /RichTextView/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /RichTextView/Images.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "29x29", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "29x29", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "40x40", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "40x40", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "60x60", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "60x60", 31 | "scale" : "3x" 32 | } 33 | ], 34 | "info" : { 35 | "version" : 1, 36 | "author" : "xcode" 37 | } 38 | } -------------------------------------------------------------------------------- /RichTextView/Images.xcassets/WatchBlack.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "scale" : "1x" 6 | }, 7 | { 8 | "idiom" : "universal", 9 | "scale" : "2x", 10 | "filename" : "Watch Black.png" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "scale" : "3x" 15 | } 16 | ], 17 | "info" : { 18 | "version" : 1, 19 | "author" : "xcode" 20 | } 21 | } -------------------------------------------------------------------------------- /RichTextView/Images.xcassets/WatchBlack.imageset/Watch Black.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kevinzhow/RichTextView/3606de2e722a1dd892094ee689cb53b033fc553c/RichTextView/Images.xcassets/WatchBlack.imageset/Watch Black.png -------------------------------------------------------------------------------- /RichTextView/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | LSRequiresIPhoneOS 24 | 25 | UILaunchStoryboardName 26 | LaunchScreen 27 | UIMainStoryboardFile 28 | Main 29 | UIRequiredDeviceCapabilities 30 | 31 | armv7 32 | 33 | UISupportedInterfaceOrientations 34 | 35 | UIInterfaceOrientationPortrait 36 | UIInterfaceOrientationLandscapeLeft 37 | UIInterfaceOrientationLandscapeRight 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /RichTextView/Source/RichTextStorage.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DiaryTextStorage.swift 3 | // Diary 4 | // 5 | // Created by kevinzhow on 15/3/5. 6 | // Copyright (c) 2015年 kevinzhow. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | 11 | public let RichTextViewDetectedDataHandlerAttributeName = "RichTextViewDetectedDataHandlerAttributeName" 12 | public let RichTextViewImageAttributeName = "RichTextViewImageAttributeName" 13 | public let RichTextViewCustomDataAttributeName = "RichTextViewCustomDataAttributeName" 14 | 15 | public enum DetectedDataType: Int, CustomStringConvertible{ 16 | case Mention = 0 17 | case HashTag 18 | case URL 19 | case Email 20 | case Image 21 | case Custom 22 | 23 | public var description: String { 24 | switch self { 25 | case .Mention: 26 | return "Mention" 27 | case .HashTag: 28 | return "HashTag" 29 | case .URL: 30 | return "URL" 31 | case .Email: 32 | return "Email" 33 | case .Image: 34 | return "Image" 35 | case .Custom: 36 | return "Custom" 37 | } 38 | } 39 | } 40 | 41 | public class RichTextStorage: NSTextStorage { 42 | 43 | public var defaultTextStyle: [NSAttributedString.Key: Any]? 44 | 45 | var backingStore: NSMutableAttributedString = NSMutableAttributedString() 46 | 47 | var mentionRanges = [NSRange]() 48 | 49 | var hashTagRanges = [NSRange]() 50 | 51 | var emailRanges = [NSRange]() 52 | 53 | var urlRanges = [NSRange]() 54 | 55 | var tapAreaInsets = UIEdgeInsets(top: -5, left: -5, bottom: -5, right: -5) 56 | 57 | public var customRanges = [NSRange]() 58 | 59 | override public var string: String { 60 | return backingStore.string 61 | } 62 | 63 | 64 | override public func attributes(at location: Int, effectiveRange range: NSRangePointer?) -> [NSAttributedString.Key : Any] { 65 | return backingStore.attributes(at: location, effectiveRange: range) 66 | } 67 | 68 | override public func replaceCharacters(in range: NSRange, with str: String) { 69 | // println("replaceCharactersInRange:\(range) withString:\(str)")z 70 | 71 | beginEditing() 72 | backingStore.replaceCharacters(in: range, with:str) 73 | edited([.editedCharacters, .editedAttributes], range: range, changeInLength: (str as NSString).length - range.length) 74 | endEditing() 75 | } 76 | 77 | 78 | public override func setAttributes(_ attrs: [NSAttributedString.Key : Any]?, range: NSRange) { 79 | beginEditing() 80 | backingStore.setAttributes(attrs, range: range) 81 | edited(.editedAttributes, range: range, changeInLength: 0) 82 | endEditing() 83 | } 84 | 85 | 86 | public override func addAttributes(_ attrs: [NSAttributedString.Key : Any] = [:], range: NSRange) { 87 | beginEditing() 88 | backingStore.addAttributes(attrs, range: range) 89 | edited(.editedAttributes, range: range, changeInLength: 0) 90 | endEditing() 91 | } 92 | 93 | override public func processEditing() { 94 | 95 | let paragraphRange = (self.string as NSString).paragraphRange(for: self.editedRange) 96 | 97 | self.removeAttribute(NSAttributedString.Key.foregroundColor, range: paragraphRange) 98 | self.removeAttribute(NSAttributedString.Key.link, range: paragraphRange) 99 | self.removeAttribute(NSAttributedString.Key(rawValue: RichTextViewDetectedDataHandlerAttributeName), range: paragraphRange) 100 | 101 | if let defaultTextStyle = defaultTextStyle { 102 | addAttributes(defaultTextStyle, range: paragraphRange) 103 | } 104 | 105 | mentionRanges = [NSRange]() 106 | 107 | hashTagRanges = [NSRange]() 108 | 109 | emailRanges = [NSRange]() 110 | 111 | urlRanges = [NSRange]() 112 | 113 | //For Mention 114 | 115 | let mentionPattern = "@[^\\s::,,@]+$?" 116 | 117 | let mentionExpression = try? NSRegularExpression(pattern: mentionPattern, options: NSRegularExpression.Options()) 118 | 119 | if let mentionExpression = mentionExpression { 120 | mentionExpression.enumerateMatches(in: self.string, options: NSRegularExpression.MatchingOptions(), range: paragraphRange, using: { (result, flags, stop) -> Void in 121 | 122 | if let result = result { 123 | let textValue = (self.string as NSString).substring(with: result.range) 124 | 125 | let textAttributes: [NSAttributedString.Key : Any]! = [NSAttributedString.Key.foregroundColor: UIColor.blue, NSAttributedString.Key.link: textValue, NSAttributedString.Key(rawValue: RichTextViewDetectedDataHandlerAttributeName): DetectedDataType.Mention.rawValue] 126 | 127 | self.addAttributes(textAttributes, range: result.range ) 128 | 129 | self.mentionRanges.append(result.range) 130 | } 131 | 132 | 133 | }) 134 | } 135 | 136 | //For Link 137 | 138 | let linkPattern = "[a-zA-Z]+://[0-9a-zA-Z_.?&/=]+" 139 | 140 | let linkExpression = try? NSRegularExpression(pattern: linkPattern, options: NSRegularExpression.Options()) 141 | 142 | if let linkExpression = linkExpression { 143 | linkExpression.enumerateMatches(in: self.string, options: NSRegularExpression.MatchingOptions(), range: paragraphRange, using: { (result, flags, stop) -> Void in 144 | 145 | if let result = result { 146 | let textValue = (self.string as NSString).substring(with: result.range) 147 | 148 | let textAttributes: [NSAttributedString.Key : Any]! = [NSAttributedString.Key.foregroundColor: UIColor.blue, NSAttributedString.Key.link: textValue, NSAttributedString.Key(rawValue: RichTextViewDetectedDataHandlerAttributeName): DetectedDataType.URL.rawValue] 149 | 150 | self.addAttributes(textAttributes, range: result.range ) 151 | 152 | self.urlRanges.append(result.range) 153 | } 154 | 155 | 156 | }) 157 | } 158 | 159 | //For HashTag 160 | 161 | let hashTagPattern = "#.+?#" 162 | 163 | let hashTagExpression = try? NSRegularExpression(pattern: hashTagPattern, options: NSRegularExpression.Options()) 164 | 165 | if let hashTagExpression = hashTagExpression { 166 | hashTagExpression.enumerateMatches(in: self.string, options: NSRegularExpression.MatchingOptions(), range: paragraphRange, using: { (result, flags, stop) -> Void in 167 | 168 | if let result = result { 169 | let textValue = (self.string as NSString).substring(with: result.range) 170 | 171 | let textAttributes: [NSAttributedString.Key : Any]! = [NSAttributedString.Key.foregroundColor: UIColor.blue, NSAttributedString.Key.link: textValue, NSAttributedString.Key(rawValue: RichTextViewDetectedDataHandlerAttributeName): DetectedDataType.HashTag.rawValue] 172 | 173 | self.addAttributes(textAttributes, range: result.range ) 174 | 175 | self.hashTagRanges.append(result.range) 176 | } 177 | 178 | }) 179 | } 180 | 181 | //For Email 182 | 183 | let emailPattern = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]+" 184 | 185 | let emailExpression = try? NSRegularExpression(pattern: emailPattern, options: NSRegularExpression.Options()) 186 | 187 | if let emailExpression = emailExpression { 188 | emailExpression.enumerateMatches(in: self.string, options: NSRegularExpression.MatchingOptions(), range: paragraphRange, using: { (result, flags, stop) -> Void in 189 | 190 | if let result = result { 191 | let textValue = (self.string as NSString).substring(with: result.range) 192 | 193 | let textAttributes: [NSAttributedString.Key : Any]! = [NSAttributedString.Key.foregroundColor: UIColor.blue, NSAttributedString.Key.link: textValue, NSAttributedString.Key(rawValue: RichTextViewDetectedDataHandlerAttributeName): DetectedDataType.Email.rawValue] 194 | 195 | self.addAttributes(textAttributes, range: result.range ) 196 | 197 | self.emailRanges.append(result.range) 198 | } 199 | 200 | }) 201 | } 202 | 203 | //For Custom Range 204 | 205 | for range in customRanges { 206 | let textAttributes:[NSAttributedString.Key : Any]! = [NSAttributedString.Key.foregroundColor: UIColor.blue, NSAttributedString.Key.link: "CustomRange", NSAttributedString.Key(rawValue: RichTextViewDetectedDataHandlerAttributeName): DetectedDataType.Custom.rawValue] 207 | 208 | self.addAttributes(textAttributes, range: range ) 209 | } 210 | 211 | super.processEditing() 212 | } 213 | 214 | 215 | } 216 | -------------------------------------------------------------------------------- /RichTextView/Source/RichTextView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // RichTextView.swift 3 | // 4 | // 5 | // Created by kevinzhow on 15/7/8. 6 | // 7 | // 8 | 9 | import UIKit 10 | 11 | public class RichTextView: UITextView { 12 | 13 | /* 14 | // Only override drawRect: if you perform custom drawing. 15 | // An empty implementation adversely affects performance during animation. 16 | override func drawRect(rect: CGRect) { 17 | // Drawing code 18 | } 19 | */ 20 | 21 | public var clickedOnData: ((_ string: String, _ dataType: DetectedDataType, _ range: NSRange) -> Void)? 22 | 23 | public var currentDetactedData: ((_ string: String, _ dataType: DetectedDataType, _ range: NSRange) -> Void)? 24 | 25 | var richTextStorage = RichTextStorage() 26 | 27 | var richLayoutManager = NSLayoutManager() 28 | 29 | var richTextContainer = NSTextContainer() 30 | 31 | public var placeHolderLabel = UILabel(frame: CGRect.zero) 32 | 33 | public var shouldUpdate = true 34 | 35 | public var linkGestureRecognizer: UITapGestureRecognizer? 36 | 37 | public let tapAreaInsets = UIEdgeInsets(top: -2, left: -2, bottom: -2, right: -2) 38 | 39 | public var tapHighLightColor = UIColor.black.withAlphaComponent(0.2) 40 | 41 | public var placeholder: String? { 42 | didSet { 43 | var attributes = [NSAttributedString.Key: Any]() 44 | 45 | if typingAttributes.count > 0 && isFirstResponder { 46 | attributes = typingAttributes 47 | } else { 48 | if let font = font { 49 | attributes[NSAttributedString.Key.font] = font 50 | } 51 | 52 | attributes[NSAttributedString.Key.foregroundColor] = UIColor(white: 0.7, alpha: 1.0) 53 | 54 | if textAlignment != NSTextAlignment.left { 55 | let paragraph = NSMutableParagraphStyle() 56 | paragraph.alignment = textAlignment 57 | attributes[NSAttributedString.Key.paragraphStyle] = paragraph 58 | } 59 | } 60 | 61 | self.attributedPlaceholder = NSAttributedString(string: placeholder!, attributes: attributes) 62 | } 63 | } 64 | 65 | public var attributedPlaceholder: NSAttributedString? { 66 | didSet { 67 | setupPlaceHolderLabel() 68 | } 69 | } 70 | 71 | func setupPlaceHolderLabel() { 72 | placeHolderLabel.attributedText = attributedPlaceholder 73 | 74 | placeHolderLabel.sizeToFit() 75 | 76 | placeHolderLabel.frame = placeholderRectForBounds(bounds: placeHolderLabel.bounds) 77 | } 78 | 79 | override public init(frame: CGRect, textContainer: NSTextContainer?) { 80 | super.init(frame: frame, textContainer: textContainer) 81 | initialize() 82 | } 83 | 84 | required public init?(coder aDecoder: NSCoder) { 85 | super.init(coder: aDecoder) 86 | initialize() 87 | } 88 | 89 | init(frame: CGRect) { 90 | richTextStorage.addLayoutManager(richLayoutManager) 91 | richLayoutManager.addTextContainer(richTextContainer) 92 | 93 | super.init(frame: frame, textContainer: richTextContainer) 94 | 95 | initialize() 96 | } 97 | 98 | func initialize() { 99 | 100 | placeHolderLabel.isHidden = false 101 | 102 | addSubview(placeHolderLabel) 103 | 104 | NotificationCenter.default.addObserver(self, selector: #selector(textChanged), name: UITextView.textDidChangeNotification, object: self) 105 | } 106 | 107 | public override var isEditable: Bool { 108 | didSet { 109 | if isEditable { 110 | 111 | if let linkGestureRecognizer = linkGestureRecognizer { 112 | self.removeGestureRecognizer(linkGestureRecognizer) 113 | } 114 | 115 | } else { 116 | linkGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(linkAction)) 117 | linkGestureRecognizer?.delegate = self 118 | self.addGestureRecognizer(linkGestureRecognizer!) 119 | } 120 | } 121 | } 122 | 123 | @objc func linkAction(sender: UITapGestureRecognizer) { 124 | 125 | let location = sender.location(in: self) 126 | 127 | enumerateLinkRangesContainingLocation(location: location, complete: { (range) -> Void in 128 | 129 | if let dataType = self.attributedText?.attribute(NSAttributedString.Key.init(RichTextViewDetectedDataHandlerAttributeName), at: range.location, effectiveRange: nil) as? Int { 130 | 131 | let textString: NSString = self.text! as NSString 132 | 133 | let valueText = textString.substring(with: range) 134 | 135 | self.handleClickedOnData(string: valueText, dataType: DetectedDataType(rawValue: dataType)!, range: range) 136 | 137 | } else if let dataType = self.attributedText?.attribute(NSAttributedString.Key.init(RichTextViewImageAttributeName), at: range.location, effectiveRange: nil) as? String { 138 | 139 | self.handleClickedOnData(string: dataType, dataType: DetectedDataType.Image, range: range) 140 | } 141 | }) 142 | } 143 | 144 | func enumerateLinkRangesContainingLocation(location: CGPoint, complete: @escaping (NSRange) -> Void) { 145 | 146 | var found = false 147 | 148 | self.attributedText.enumerateAttribute(NSAttributedString.Key(rawValue: RichTextViewDetectedDataHandlerAttributeName), in: NSMakeRange(0, attributedText.length), options: [], using: { (value, range, stop) in 149 | 150 | if let _: AnyObject = value as AnyObject { 151 | 152 | self.enumerateViewRectsForRanges([NSValue(range: range)], complete: { (rect, range, stop) -> Void in 153 | 154 | if !found { 155 | 156 | if rect.contains(location) { 157 | 158 | self.drawRoundedCornerForRange(range: range, rect: rect) 159 | 160 | found = true 161 | 162 | complete(range) 163 | } 164 | } else { 165 | // println("Found") 166 | } 167 | }) 168 | } 169 | }) 170 | 171 | if !found { 172 | self.attributedText.enumerateAttribute(NSAttributedString.Key(rawValue: RichTextViewImageAttributeName), in: NSMakeRange(0, attributedText.length), options: [], using: { (value, range, stop) in 173 | 174 | if let _ = value { 175 | 176 | self.enumerateViewRectsForRanges([NSValue(range: range)], complete: { (rect, range, stop) -> Void in 177 | 178 | if !found { 179 | 180 | if rect.contains(location) { 181 | 182 | self.drawRoundedCornerForRange(range: range, rect: rect) 183 | 184 | found = true 185 | 186 | complete(range) 187 | } 188 | 189 | } else { 190 | // println("Found") 191 | } 192 | }) 193 | } 194 | }) 195 | } 196 | 197 | return 198 | } 199 | 200 | func enumerateViewRectsForRanges(_ ranges: [NSValue], complete: @escaping (_ rect: CGRect, _ range: NSRange, _ stop: Bool) -> Void) { 201 | 202 | for rangeValue in ranges { 203 | 204 | let range = rangeValue.rangeValue 205 | 206 | let glyphRange = layoutManager.glyphRange(forCharacterRange: range, actualCharacterRange: nil) 207 | 208 | layoutManager.enumerateEnclosingRects(forGlyphRange: glyphRange, withinSelectedGlyphRange: NSMakeRange(NSNotFound, 0), in: textContainer, using: { (rect, stop) -> Void in 209 | var rect = rect 210 | 211 | rect.origin.x += self.textContainerInset.left 212 | rect.origin.y += self.textContainerInset.top 213 | rect = rect.inset(by: self.tapAreaInsets) 214 | 215 | complete(rect, range, true) 216 | }) 217 | 218 | } 219 | 220 | return 221 | } 222 | 223 | func drawRoundedCornerForRange(range: NSRange, rect: CGRect) { 224 | 225 | let layer = CALayer() 226 | layer.frame = rect 227 | layer.backgroundColor = tapHighLightColor.cgColor 228 | layer.cornerRadius = 3.0 229 | layer.masksToBounds = true 230 | self.layer.addSublayer(layer) 231 | 232 | delay(delay: 0.2, closure: { () -> () in 233 | layer.removeFromSuperlayer() 234 | }) 235 | 236 | } 237 | 238 | @objc func textChanged() { 239 | if let _ = attributedPlaceholder { 240 | if (text as NSString).length == 0 { 241 | placeHolderLabel.isHidden = false 242 | } else { 243 | placeHolderLabel.isHidden = true 244 | } 245 | } 246 | 247 | self.setNeedsDisplay() 248 | } 249 | 250 | func handleClickedOnData(string: String, dataType: DetectedDataType, range: NSRange ){ 251 | if let clickedOnData = clickedOnData { 252 | clickedOnData(string, dataType, range) 253 | } 254 | } 255 | 256 | func handleCurrentDetactedData(string: String, dataType: DetectedDataType, range: NSRange) { 257 | if let currentDetactedData = currentDetactedData { 258 | currentDetactedData(string, dataType, range) 259 | } 260 | } 261 | 262 | public func appendImage(imageName: String ,image: UIImage, width: CGFloat) { 263 | 264 | if let newAttributedText = self.attributedText.mutableCopy() as? NSMutableAttributedString { 265 | 266 | newAttributedText.append(NSAttributedString(string: "\n")) 267 | 268 | var _ = text.lengthOfBytes(using: String.Encoding.utf8) 269 | 270 | self.attributedText = newAttributedText 271 | 272 | let imageWidth = image.size.width 273 | 274 | let radio:CGFloat = width / imageWidth 275 | 276 | let size = CGSize(width: image.size.width*radio, height: image.size.height*radio) 277 | appendImage(imageName: imageName, image: image, size: size) 278 | 279 | appendNewLine() 280 | } 281 | } 282 | 283 | public func appendNewLine() { 284 | 285 | if let newAttributedText = self.attributedText.mutableCopy() as? NSMutableAttributedString { 286 | 287 | let newLineString = NSMutableAttributedString(string: "\n") 288 | 289 | newLineString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle(spacing: 0), range: NSRange(location: 0, length: newLineString.length)) 290 | 291 | newAttributedText.append(newLineString) 292 | 293 | attributedText = newAttributedText 294 | } 295 | 296 | } 297 | 298 | public func appendImage(imageName: String ,image: UIImage, size: CGSize){ 299 | 300 | let attachment = NSTextAttachment(data: nil, ofType: nil) 301 | attachment.image = image 302 | attachment.bounds = CGRect(x: 0, y:0, width:size.width, height:size.height) 303 | 304 | if let attachmentAttributedString = NSAttributedString(attachment: attachment) as? NSMutableAttributedString { 305 | // sets the paragraph styling of the text attachment 306 | 307 | 308 | let attr: [NSAttributedString.Key: Any] = [NSAttributedString.Key.paragraphStyle: paragraphStyle(spacing: 0), NSAttributedString.Key(rawValue: RichTextViewImageAttributeName): imageName, NSAttributedString.Key(rawValue: RichTextViewDetectedDataHandlerAttributeName): DetectedDataType.Image.rawValue] 309 | 310 | attachmentAttributedString.addAttributes(attr, range: NSRange(location: 0, length: attachmentAttributedString.length)) 311 | 312 | if let newAttributedText = self.attributedText.mutableCopy() as? NSMutableAttributedString { 313 | 314 | newAttributedText.append(attachmentAttributedString) 315 | 316 | self.attributedText = newAttributedText 317 | } 318 | } 319 | } 320 | 321 | public func findAllImageRange() -> [[String : NSRange]]?{ 322 | 323 | var finalRange = [[String : NSRange]]() 324 | 325 | self.attributedText.enumerateAttribute(NSAttributedString.Key(rawValue: RichTextViewImageAttributeName), in: NSRange(location: 0, length: self.attributedText.length), options: [], using: { (value, range, finish) in 326 | 327 | if let value = value as? String { 328 | finalRange.append([value : range]) 329 | } 330 | 331 | }) 332 | 333 | if finalRange.count > 0 { 334 | return finalRange 335 | } else { 336 | return nil 337 | } 338 | 339 | } 340 | 341 | public func findImageRange(imageHash: String) -> NSRange?{ 342 | 343 | var finalRange: NSRange? 344 | 345 | self.attributedText.enumerateAttribute(NSAttributedString.Key(rawValue: RichTextViewImageAttributeName), in: NSRange(location: 0, length: self.attributedText.length), options: [], using: { (value, range, finish) in 346 | 347 | if let value = value as? String { 348 | if value == imageHash { 349 | finalRange = range 350 | } 351 | } 352 | 353 | }) 354 | 355 | if let finalRange = finalRange { 356 | return finalRange 357 | } 358 | 359 | return nil 360 | 361 | } 362 | 363 | private func paragraphStyle(spacing: CGFloat) -> NSMutableParagraphStyle { 364 | 365 | let paragraphStyle = NSMutableParagraphStyle() 366 | 367 | paragraphStyle.paragraphSpacing = spacing 368 | 369 | paragraphStyle.paragraphSpacingBefore = spacing 370 | 371 | return paragraphStyle 372 | } 373 | 374 | public func insertImage(imageName: String, image: UIImage, size: CGSize, index: Int){ 375 | 376 | let attachment = NSTextAttachment(data: nil, ofType: nil) 377 | attachment.image = image 378 | attachment.bounds = CGRect(x:0, y:0, width:size.width, height:size.height) 379 | 380 | if let attachmentAttributedString = NSAttributedString(attachment: attachment) as? NSMutableAttributedString { 381 | // sets the paragraph styling of the text attachment 382 | 383 | let paragraphStyle = NSMutableParagraphStyle() 384 | 385 | paragraphStyle.paragraphSpacing = 10 386 | 387 | paragraphStyle.paragraphSpacingBefore = 10 388 | 389 | let attr: [NSAttributedString.Key: Any] = [NSAttributedString.Key.paragraphStyle: paragraphStyle, NSAttributedString.Key(rawValue: RichTextViewImageAttributeName): imageName, NSAttributedString.Key(rawValue: RichTextViewDetectedDataHandlerAttributeName): DetectedDataType.Image.rawValue] 390 | 391 | attachmentAttributedString.addAttributes(attr, range: NSRange(location: 0, length: attachmentAttributedString.length)) 392 | 393 | if let newAttributedText = self.attributedText.mutableCopy() as? NSMutableAttributedString { 394 | 395 | newAttributedText.insert(attachmentAttributedString, at: index) 396 | 397 | self.attributedText = newAttributedText 398 | } 399 | } 400 | } 401 | 402 | public func replaceImage(imageName: String, image: UIImage, size: CGSize, index: Int){ 403 | 404 | let attachment = NSTextAttachment(data: nil, ofType: nil) 405 | attachment.image = image 406 | attachment.bounds = CGRect(x:0, y:0, width:size.width, height:size.height) 407 | 408 | if let attachmentAttributedString = NSAttributedString(attachment: attachment) as? NSMutableAttributedString { 409 | // sets the paragraph styling of the text attachment 410 | 411 | let paragraphStyle = NSMutableParagraphStyle() 412 | 413 | paragraphStyle.paragraphSpacing = 10 414 | 415 | paragraphStyle.paragraphSpacingBefore = 10 416 | 417 | let attr: [NSAttributedString.Key: Any] = [NSAttributedString.Key.paragraphStyle: paragraphStyle, NSAttributedString.Key(rawValue: RichTextViewImageAttributeName): imageName, NSAttributedString.Key(rawValue: RichTextViewDetectedDataHandlerAttributeName): DetectedDataType.Image.rawValue] 418 | 419 | attachmentAttributedString.addAttributes(attr, range: NSRange(location: 0, length: attachmentAttributedString.length)) 420 | 421 | if let newAttributedText = self.attributedText.mutableCopy() as? NSMutableAttributedString { 422 | 423 | newAttributedText.replaceCharacters(in: NSRange(location: index, length: 1), with: attachmentAttributedString) 424 | 425 | self.attributedText = newAttributedText 426 | } 427 | } 428 | } 429 | 430 | func placeholderRectForBounds(bounds: CGRect) -> CGRect { 431 | var rect = bounds 432 | 433 | if self.responds(to: #selector(getter: UITextView.textContainer)) { 434 | let padding = self.textContainer.lineFragmentPadding 435 | rect.origin.x += padding 436 | rect.origin.y += padding * 1.5 437 | } else { 438 | if self.contentInset.left == 0.0 { 439 | rect.origin.x += 8.0 440 | } 441 | rect.origin.y += 8.0 442 | } 443 | 444 | return rect; 445 | } 446 | 447 | func delay(delay:Double, closure:@escaping ()->()) { 448 | DispatchQueue.main.asyncAfter(deadline: .now() + delay) { 449 | closure() 450 | } 451 | } 452 | } 453 | 454 | extension RichTextView: UIGestureRecognizerDelegate { 455 | public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { 456 | return true 457 | } 458 | } 459 | -------------------------------------------------------------------------------- /RichTextView/Source/RichTextViewDelegateHandler.swift: -------------------------------------------------------------------------------- 1 | // 2 | // RichTextViewDelegateHandler.swift 3 | // 4 | // 5 | // Created by kevinzhow on 15/7/9. 6 | // 7 | // 8 | 9 | import UIKit 10 | 11 | public class RichTextViewDelegateHandler: NSObject { 12 | } 13 | 14 | extension RichTextViewDelegateHandler: UITextViewDelegate { 15 | 16 | 17 | public func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { 18 | print("Should interact with Attachment") 19 | return true 20 | } 21 | 22 | public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { 23 | let textString: NSString = textView.text! as NSString 24 | 25 | let valueText = textString.substring(with: characterRange) 26 | 27 | guard let textViewAttributedText = textView.attributedText else {return false} 28 | 29 | if let dataType = textViewAttributedText.attribute(NSAttributedString.Key(rawValue: RichTextViewDetectedDataHandlerAttributeName), at: characterRange.location, effectiveRange: nil) as? Int { 30 | 31 | (textView as! RichTextView).handleClickedOnData(string: valueText, dataType: DetectedDataType(rawValue: dataType)!, range: characterRange) 32 | 33 | } 34 | 35 | return true 36 | } 37 | 38 | 39 | func textViewCurrentDetactedString(textView: UITextView, string: String, dataType: DetectedDataType, range: NSRange) { 40 | (textView as! RichTextView).handleCurrentDetactedData(string: string, dataType: dataType, range: range) 41 | } 42 | 43 | 44 | public func textViewDidChange(_ textView: UITextView) { 45 | 46 | if let textStorage = textView.layoutManager.textStorage as? RichTextStorage { 47 | 48 | let targetLocation = textView.selectedRange.location 49 | 50 | for range in textStorage.mentionRanges { 51 | if range.location >= targetLocation || range.location + range.length >= targetLocation { 52 | 53 | 54 | let textValue = (textStorage.string as NSString).substring(with: range) 55 | 56 | textViewCurrentDetactedString(textView: textView, string: textValue, dataType: DetectedDataType.Mention, range: range) 57 | 58 | return 59 | } 60 | } 61 | 62 | for range in textStorage.emailRanges { 63 | if range.location >= targetLocation || range.location + range.length >= targetLocation { 64 | 65 | let textValue = (textStorage.string as NSString).substring(with: range) 66 | 67 | textViewCurrentDetactedString(textView: textView, string: textValue, dataType: DetectedDataType.Email, range: range) 68 | 69 | return 70 | } 71 | } 72 | 73 | for range in textStorage.urlRanges { 74 | if range.location >= targetLocation || range.location + range.length >= targetLocation { 75 | 76 | let textValue = (textStorage.string as NSString).substring(with: range) 77 | 78 | textViewCurrentDetactedString(textView: textView, string: textValue, dataType: DetectedDataType.URL, range: range) 79 | 80 | return 81 | } 82 | } 83 | 84 | for range in textStorage.hashTagRanges { 85 | if range.location >= targetLocation || range.location + range.length >= targetLocation { 86 | 87 | let textValue = (textStorage.string as NSString).substring(with: range) 88 | 89 | textViewCurrentDetactedString(textView: textView, string: textValue, dataType: DetectedDataType.HashTag, range: range) 90 | 91 | return 92 | } 93 | } 94 | 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /RichTextView/ViewController.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.swift 3 | // RichTextView 4 | // 5 | // Created by kevinzhow on 15/7/8. 6 | // Copyright (c) 2015年 kevinzhow. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | 11 | class ViewController: UIViewController { 12 | 13 | var CommentReplyTextViewStyle : [NSAttributedString.Key : Any] { 14 | get { 15 | 16 | let paraStyle = NSMutableParagraphStyle() 17 | 18 | paraStyle.lineBreakMode = .byWordWrapping 19 | 20 | return [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15.0), 21 | NSAttributedString.Key.paragraphStyle: paraStyle 22 | ] 23 | } 24 | } 25 | 26 | @IBOutlet weak var replaceButton: UIButton! 27 | 28 | var richTextViewDelegate = RichTextViewDelegateHandler() //Subclass this to Modify your needs and Make sure it will retain 29 | 30 | 31 | lazy var richTextView: RichTextView = { 32 | let view = RichTextView(frame: CGRect.zero) 33 | view.translatesAutoresizingMaskIntoConstraints = false 34 | view.textContainer.lineBreakMode = .byWordWrapping 35 | 36 | view.delaysContentTouches = false 37 | 38 | // richTextView.textContainer.lineFragmentPadding = 0 39 | 40 | view.font = UIFont.systemFont(ofSize: 15.0) 41 | 42 | view.isScrollEnabled = true 43 | view.textContainerInset = UIEdgeInsets.zero 44 | view.isEditable = true // true for realtime editing 45 | 46 | view.isSelectable = true 47 | (view.textStorage as! RichTextStorage).defaultTextStyle = CommentReplyTextViewStyle 48 | return view 49 | }() 50 | 51 | var currentRange: NSRange? 52 | 53 | func sizeHeightWithText(attrString: NSString, width: CGFloat, textAttributes: [NSAttributedString.Key : Any]) -> CGSize { 54 | 55 | // var attributeString = NSAttributedString(string: attrString as String, attributes: textAttributes) 56 | 57 | // var line = CTLineCreateWithAttributedString(attributeString) 58 | // var bounds = CTLineGetBoundsWithOptions(line, CTLineBoundsOptions.UseGlyphPathBounds) 59 | 60 | let rect = attrString.boundingRect(with: CGSize(width: width, height:CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: textAttributes, context: nil) 61 | 62 | return CGSize(width: ceil(rect.width), height: ceil(rect.height)) 63 | } 64 | 65 | 66 | @IBAction func replaceWithUser(sender: AnyObject) { 67 | if let currentRange = currentRange { 68 | 69 | richTextView.textStorage.replaceCharacters(in: currentRange, with: "@kevinzhow") 70 | 71 | richTextView.selectedRange = NSMakeRange(currentRange.location + "@kevinzhow".count, 0) 72 | } 73 | } 74 | 75 | override func viewDidLoad() { 76 | super.viewDidLoad() 77 | 78 | richTextView.delegate = richTextViewDelegate 79 | richTextView.text = "I am @kevinzhow and My email is kevinchou.c@gmail.com #Catch# \n you can find my blog at http://zhowkev.in" 80 | 81 | _ = sizeHeightWithText(attrString: richTextView.text! as NSString, width: 350, textAttributes: CommentReplyTextViewStyle) 82 | 83 | richTextView.currentDetactedData = { (string, dataType, range) in 84 | print("Current \(dataType.description) with \(string) at \(range)") 85 | 86 | self.currentRange = range 87 | 88 | self.view.bringSubviewToFront(self.replaceButton) 89 | } 90 | 91 | richTextView.clickedOnData = { (string, dataType, range) in 92 | print("Clicked On \(dataType.description) with \(string)") 93 | } 94 | 95 | // richTextView.insertImage("smallWatch", image: UIImage(named: "WatchBlack")!, size: CGSize(width: 10, height: 10), index: 2) 96 | 97 | let imageWidth = self.view.frame.width - 10 98 | richTextView.appendImage(imageName: "bigWatch", image: UIImage(named: "WatchBlack")!, width: imageWidth) 99 | 100 | print(richTextView.attributedText) 101 | let ranges = richTextView.findAllImageRange() 102 | 103 | print(ranges) 104 | 105 | view.addSubview(richTextView) 106 | 107 | richTextView.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor).isActive = true 108 | richTextView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor).isActive = true 109 | richTextView.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor).isActive = true 110 | richTextView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor).isActive = true 111 | 112 | 113 | // Do any additional setup after loading the view, typically from a nib. 114 | } 115 | 116 | override func viewDidLayoutSubviews() { 117 | super.viewDidLayoutSubviews() 118 | 119 | 120 | } 121 | 122 | override func didReceiveMemoryWarning() { 123 | super.didReceiveMemoryWarning() 124 | // Dispose of any resources that can be recreated. 125 | } 126 | 127 | 128 | } 129 | 130 | -------------------------------------------------------------------------------- /RichTextViewTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /RichTextViewTests/RichTextViewTests.swift: -------------------------------------------------------------------------------- 1 | // 2 | // RichTextViewTests.swift 3 | // RichTextViewTests 4 | // 5 | // Created by kevinzhow on 15/7/8. 6 | // Copyright (c) 2015年 kevinzhow. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | import XCTest 11 | 12 | class RichTextViewTests: XCTestCase { 13 | 14 | override func setUp() { 15 | super.setUp() 16 | // Put setup code here. This method is called before the invocation of each test method in the class. 17 | } 18 | 19 | override func tearDown() { 20 | // Put teardown code here. This method is called after the invocation of each test method in the class. 21 | super.tearDown() 22 | } 23 | 24 | func testExample() { 25 | // This is an example of a functional test case. 26 | XCTAssert(true, "Pass") 27 | } 28 | 29 | func testPerformanceExample() { 30 | // This is an example of a performance test case. 31 | self.measureBlock() { 32 | // Put the code you want to measure the time of here. 33 | } 34 | } 35 | 36 | } 37 | --------------------------------------------------------------------------------