1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
extension
UITextView
{
//添加连接文本(连接为空时则表示普通文本)
func
appendLinkString(string:
String
, withURLString:
String
=
""
) {
//原来的文本内容
let
attrString:
NSMutableAttributedString
=
NSMutableAttributedString
()
attrString.appendAttributedString(
self
.attributedText)
//新增的文本内容(使用默认设置的字体样式)
let
attrs = [
NSFontAttributeName
:
self
.font!]
let
appendString =
NSMutableAttributedString
(string: string, attributes:attrs)
//判断是不是连接文字
if
withURLString !=
""
{
let
range:
NSRange
=
NSMakeRange
(0, appendString.length)
appendString.beginEditing()
appendString.addAttribute(
NSLinkAttributeName
, value:withURLString, range:range)
appendString.endEditing()
}
//合并新的文本
attrString.appendAttributedString(appendString)
//设置合并后的文本
self
.attributedText = attrString
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
import
UIKit
class
ViewController
:
UIViewController
,
UITextViewDelegate
{
@IBOutlet
weak
var
textView:
UITextView
!
override
func
viewDidLoad() {
super
.viewDidLoad()
//设置展现文本框的代理
textView.delegate =
self
textView.text =
""
textView.appendLinkString(
"欢迎使用航歌APP!\n"
)
textView.appendLinkString(
"(1)"
)
textView.appendLinkString(
"查看详细说明"
, withURLString:
"about:from123"
)
textView.appendLinkString(
"\n(2)"
)
textView.appendLinkString(
"问题反馈"
, withURLString:
"feedback:from234"
)
}
//连接点击响应方法
func
textView(textView:
UITextView
, shouldInteractWithURL
URL
:
NSURL
,
inRange characterRange:
NSRange
) ->
Bool
{
switch
URL
.scheme {
case
"about"
:
showAlert(
"about"
,
payload:
URL
.resourceSpecifier.stringByRemovingPercentEncoding!)
case
"feedback"
:
showAlert(
"feedback"
,
payload:
URL
.resourceSpecifier.stringByRemovingPercentEncoding!)
default
:
print
(
"这个是普通的url"
)
}
return
true
}
//显示消息
func
showAlert(tagType:
String
, payload:
String
){
let
alertController =
UIAlertController
(title:
"检测到\(tagType)标签"
,
message: payload, preferredStyle: .
Alert
)
let
cancelAction =
UIAlertAction
(title:
"肯定"
, style: .
Cancel
, handler:
nil
)
alertController.addAction(cancelAction)
self
.presentViewController(alertController, animated:
true
, completion:
nil
)
}
}
|