首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在UiTextView中插入一个数字并检测该数字

在UiTextView中插入一个数字并检测该数字
EN

Stack Overflow用户
提问于 2017-07-16 20:03:06
回答 1查看 1.7K关注 0票数 1

我有一个UITextView,它包含很多结尾带有数字的文本。我正在尝试检测文本视图中的数字,但无法实现。我只能找到解决方案,只能找到链接。

我正在使用NSAttributedString来显示文本。

.dataDetectorTypes似乎不起作用。有人能帮我吗?

我正试着这样做。

代码语言:javascript
复制
let middleTextView: UITextView = {
        let tv = UITextView();
        let attributedText = NSMutableAttributedString(string: "Your NetCode will be sent to", attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 14)]);
        attributedText.append(NSAttributedString(string: "\n\nXXXX XXX 252", attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 16)]));
        attributedText.append(NSMutableAttributedString(string: "\n\n To update you mobile number call tel://13 2221", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)]));
//        let url = NSURL(string: "tel://\(1234)");
//        tv.text = url;
        tv.attributedText = attributedText;
        tv.textAlignment = .center
        tv.backgroundColor = UIColor.clear;
        tv.dataDetectorTypes = .phoneNumber;
        tv.isEditable = false;
        tv.isSelectable = false;
        tv.translatesAutoresizingMaskIntoConstraints = false;
        return tv;
    }();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-16 20:38:40

我看到您使用的是Swift 4的NSAttributedStringKey,所以我在您的问题中添加了这个标签。

您必须手动创建电话URL并设置isSelectable = true,否则在文本视图中不会发生交互:

代码语言:javascript
复制
let middleTextView: UITextView = {
    let attributedText = NSMutableAttributedString(string: "Your NetCode will be sent to", attributes: [.font : UIFont.systemFont(ofSize: 14)])
    attributedText.append(NSAttributedString(string: "\n\nXXXX XXX 252", attributes: [.font: UIFont.boldSystemFont(ofSize: 16)]))
    attributedText.append(NSAttributedString(string: "\n\n To update you mobile number ", attributes: [.font: UIFont.systemFont(ofSize: 12)]))

    let phoneNumber = "13 2221"
    let phoneNumberAttributes: [NSAttributedStringKey: Any] = [
        .font: UIFont.systemFont(ofSize: 12),
        .foregroundColor: UIColor.blue,
        .link: URL(string: "tel://" + phoneNumber.replacingOccurrences(of: " ", with: ""))!,
    ]
    attributedText.append(NSAttributedString(string: phoneNumber, attributes: phoneNumberAttributes))

    tv.attributedText = attributedText
    tv.textAlignment = .center
    tv.backgroundColor = UIColor.clear
    tv.isEditable = false
    tv.isSelectable = true // you must set this to true
    return tv
}()
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45128370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档