如何在Swift中为Label添加文字描边(Outline/Stroke)?
嘿,我懂你想要的那种文字描边效果——shadow属性确实只能做出阴影,没法实现真正的文字轮廓,这玩意儿我当初也踩过坑!下面给你几个在Swift里给UILabel添加白色文字描边的实用方案,亲测适配iOS各个版本:
方法1:自定义UILabel子类(推荐长期复用)
如果你的项目里多个地方需要这种描边Label,自定义子类是最高效的方式,以后直接拖控件改类就行:
import UIKit class StrokedLabel: UILabel { // 可配置的描边属性,方便在代码或Storyboard里调整 @IBInspectable var strokeColor: UIColor = .white @IBInspectable var strokeWidth: CGFloat = 2.0 override func drawText(in rect: CGRect) { // 组合文字属性:原文字颜色 + 外侧描边 let textAttributes: [NSAttributedString.Key: Any] = [ .foregroundColor: self.textColor, .strokeColor: strokeColor, .strokeWidth: -strokeWidth // 划重点:负数才是外侧描边,正数会变成空心字 ] self.attributedText = NSAttributedString(string: self.text ?? "", attributes: textAttributes) super.drawText(in: rect) } }
怎么用?
- Storyboard/XIB方式:拖一个UILabel到界面,在Identity Inspector里把Class改成
StrokedLabel,然后就能在Attributes Inspector里直接调整strokeColor和strokeWidth了,跟设置普通Label属性一样方便。 - 代码创建方式:
let myStrokedLabel = StrokedLabel(frame: CGRect(x: 50, y: 100, width: 280, height: 60)) myStrokedLabel.text = "Yo Dawg!" myStrokedLabel.textColor = .black // 文字主体颜色 myStrokedLabel.strokeColor = .white // 描边颜色 myStrokedLabel.strokeWidth = 2.5 // 描边粗细 myStrokedLabel.font = UIFont.boldSystemFont(ofSize: 32) view.addSubview(myStrokedLabel)
方法2:直接用NSAttributedString(适合临时单个Label)
如果只是某个Label需要描边,不想写子类,直接给Label的attributedText赋值就行:
let tempLabel = UILabel(frame: CGRect(x: 50, y: 200, width: 280, height: 60)) tempLabel.font = UIFont.boldSystemFont(ofSize: 32) tempLabel.textColor = .black // 构建描边属性 let strokeAttrs: [NSAttributedString.Key: Any] = [ .strokeColor: UIColor.white, .strokeWidth: -2.5, .foregroundColor: tempLabel.textColor ] tempLabel.attributedText = NSAttributedString(string: "Yo Dawg!", attributes: strokeAttrs) view.addSubview(tempLabel)
小提醒
一定要注意strokeWidth的正负:正数会让描边在文字内部,看起来文字是空心的;只有负数才是你要的外侧描边,和你参考图里的效果完全匹配。
内容的提问来源于stack exchange,提问作者Karliene
相关产品推荐
相关产品推荐

