如何为按钮中的文本添加边框?

How to add border to text in a button?

我有一个带有一些文本的按钮,我需要为其添加边框,这是 0.2 像素的文本,我使用了 @IBDesignable 但它适用于按钮而不适用于文本。

我的代码:

@IBInspectable var borderWidth: CGFloat = 1.0{
        didSet{
            layer.borderWidth = borderWidth
        }
    }
    @IBInspectable var borderTextColor:UIColor?{
        didSet{
            layer.borderColor = borderTextColor?.cgColor
        }
    }

你可以简单地给按钮一个 ID & 只需使用正常的 CSS 就像这样-

#myButton{text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000;}

这只会为您的文本创建一个阴影轮廓。根据您的需要管理颜色。

您正在为 UIButton 而不是 UILabel 添加边框。将 UILabel 用于文本而不是 UIButton 文本,然后像这样

将边框分配给 UILabel
    yourLabel.layer.borderColor = UIColor.black.cgColor
    yourLabel.layer.borderWidth = 2
    yourLabel.layer.cornerRadius = 5

如果您想为文本本身添加边框,您可以使用属性字符串为文本添加笔画。您可以对 UIKit 中大多数与文本相关的 UI 元素执行此操作,例如 UILabelUIButton

// Create the stroke attributes
let attributes: [NSAttributedString.Key: Any] = [
    NSAttributedString.Key.strokeColor: UIColor.black,
    NSAttributedString.Key.foregroundColor: UIColor.white,
    NSAttributedString.Key.strokeWidth: -4.0
];

// Create the text with a stroke as an attributed string
let textWithStroke = NSAttributedString(
    string: "Button Text",
    attributes: attributes
);

// Set the attributed string to the button
button.setAttributedTitle(textWithStroke, for: .normal);

.strokeWidth 使用负值,这样笔划勾勒出文本的外部而不是内部

如果要编辑字体,只需将值为 UIFontNSAttributedString.Key.font 键添加到 attributes 数组