nai*_*iyu 6 html tags uilabel swift
这是我的代码,显示 UILabel 中的链接
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textFiled: UITextField!
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let attrStr = try! NSAttributedString(
data: "This is a link <a href='http://www.google.com'>google</a>".dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
label.attributedText = attrStr
}
}
Run Code Online (Sandbox Code Playgroud)
从图片中可以看到,它正确显示了我想要的链接,但该链接无法单击跳转到网页视图或其他视图。实际上,我需要自定义链接点击事件,但我真的不知道:
感谢您首先检查这个问题。
正如 Luke 所说,UILabels 不支持 URL。但您可以创建一个看起来像标签的按钮。去掉背景(所以它看起来像文本)并为按钮实现打开 webview 的功能。您可以使用属性字符串来编辑按钮中文本的样式。
当您将按钮添加到 UI 时,您将需要考虑使用自定义类而不是默认的 uibutton 类。
您将需要:
在里面
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self)
{
//call the method to configure the button
[self configure];
}
return self;
}
Run Code Online (Sandbox Code Playgroud)如果您使用属性字符串,请实现 setTitle 或 setAttributedTitle
- (void) setTitle:(NSString *)title forState:(UIControlState)state
{
[super setTitle:title forState:state]
}
Run Code Online (Sandbox Code Playgroud)或者
- (void)setAttributedTitle:(NSAttributedString *)title forState: (UIControlState)state{
[super setAttributedTitle:title forState:state];
}
Run Code Online (Sandbox Code Playgroud)
3.配置按钮
-(void) configure{
//configure the buttons label here
//you will want to set no background colour
}
Run Code Online (Sandbox Code Playgroud)
4.将按钮添加到viewcontroller并将类更改为您创建的自定义类。