Swift HTML富文本显示

来源:互联网 发布:淘宝一颗钻多少钱 编辑:程序博客网 时间:2024/06/06 11:46

iOS平台下更灵活

    override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view, typically from a nib.        var strHtml = "<html><body> Hello <span style=\"color:#0f0;font-size:30px;\">It is me.</span>"        strHtml += "<br/> <font size=\"13\" color=\"red\">Here you are, Here we are!</font>;</body></html>";                let label:UILabel = UILabel()        label.text = strHtml        label.numberOfLines = 0 //Line break when the current line is full display.        label.lineBreakMode = NSLineBreakMode.byClipping;//Tips:Supported six types.                do{            let srtData= strHtml.data(using: String.Encoding.unicode, allowLossyConversion: true)!            let strOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]//Tips:Supported four types.            let attrStr = try NSAttributedString(data: srtData, options: strOptions, documentAttributes: nil)            label.attributedText = attrStr        }catch let error as NSError {            print(error.localizedDescription)        }        label.frame = CGRect(x:self.view.frame.origin.x,                             y:self.view.frame.origin.y,                             width:self.view.frame.size.width,                             height:self.view.frame.size.height);        self.view.addSubview(label)    }
android平台下更直接
@Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        String strHtml = "<html><body> Hello, <span style=color:#0f0;font-size:30;>It is me.</span>";        strHtml += "<br/> <font size=13 color=red>Here you are, Here we are!</font>;</body></html>";        TextView textView = (TextView)findViewById(R.id.text);        textView.setText(Html.fromHtml(strHtml));    }



原创粉丝点击