iOS:在文字UILabel周围绘制边框

时间:2018-08-01 14:32:20

标签: ios uilabel border nsattributedstring

我想像这样在UILabel的文本周围绘制轮廓:

enter image description here

我尝试使用属性文本,但是没有用于在文本周围呈现边框的属性。仅下划线可用。我也尝试过使用属性文本呈现html,但这也无济于事:

let htmlLabelText = String(format: "<html><body><span style='color:blue; border: 1.5px solid #55DF49; border-radius: 50px;'>%@</span></body></html>", labelText)
var attributedString = NSMutableAttributedString()
guard let stringData = data(using: .unicode) else { return NSMutableAttributedString() }
do {
    attributedString = try NSMutableAttributedString(
        data: stringData,
        options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil
    )
} catch {}

我检查了其他帖子,但是没有一个帮助。

3 个答案:

答案 0 :(得分:2)

对于UILabel来说,这个问题很难解决,因为您没有直接访问NSLayoutManager的权限,这是我解决方案的关键。

我创建了IBDesignable UILabel子类LineHighlightedLabel,可以完成此工作。视觉效果与您提供的图像不太一样,但是您可以到达那里。

重要的部分是将UILabel的文本设置为NSAttributedString,而不仅仅是纯文本。

[NSDictionary writeToURL:atomically:]

LineHighlightedLabel在界面构建器中提供了很好的预览,您可以轻松地使用值。

enter image description here

答案 1 :(得分:0)

@shota的答案也可以。

Here正是我通过不使用NSLayoutManager子类化UILabel来解决此问题的方法。尽管使用LayoutManager.enumerateLineFragments是更好的选择,但我复制了用于从stackoverflow中某处的文本获取行的代码。另外,还需要一种技巧来渲染UILabel的文本,在开始和结束处使用两个空格。这是最终结果的屏幕截图:

enter image description here

答案 2 :(得分:-1)

这是答案。

var memoryStream = new MemoryStream();
await context.ActionContext.Response.Content.CopyToAsync(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
var sr = new StreamReader(memoryStream);
var logMessage = sr.ReadToEnd();

OR

label1.layer.borderColor = [UIColor greenColor].CGColor;
label1.layer.borderWidth =1.0

OR

label2.layer.borderColor = [UIColor blueColor].CGColor;
label1.layer.borderWidth =5.0

尝试这些不同的可能性。

相关问题