iOS - 如何删除 UIButton 边框颜色?

Posted

技术标签:

【中文标题】iOS - 如何删除 UIButton 边框颜色?【英文标题】:iOS - How to Remove UIButton border color? 【发布时间】:2018-05-02 05:55:42 【问题描述】:

当前按钮设置

button.backgroundColor = UIColor.brown
button.layer.cornerRadius = 60/2
button.layer.borderWidth = 5
button.layer.borderColor = UIColor.white.cgColor

看起来像上面的代码 问题是,外面有一个很细的边框,如下图所示。

边框颜色和你设置的backgroundColor一样。 将backgroundColor 更改为红色会将底部边框更改为红色。

我设置了button.layer.shadowColor。 按钮大小为60,使用anchor设置宽/高。

仍在寻找。但只有borderColor设置。 这令人沮丧。请寻求帮助。为什么会这样?

【问题讨论】:

尝试移除 shadowColor 或将其设置为清晰 边框如预期的那样是白色的,但出现的细边框似乎是阴影。所以尽量去掉阴影或者清除shadowColor 参考link可能对你有帮助 @Mr.Kushwaha - 我没有设置阴影选项。我尝试了清晰的颜色,但失败了。 @PPL - 已应用圆角。但是按钮没有显示哈哈:( 【参考方案1】:

您可以通过这种方式实现 UIView 扩展,

extension UIView 
    func roundCorners(_ corners: UIRectCorner, radius: CGFloat, borderColor: UIColor, borderWidth: CGFloat) 
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))

        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask

        let borderPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let borderLayer = CAShapeLayer()
        borderLayer.path = borderPath.cgPath
        borderLayer.lineWidth = borderWidth
        borderLayer.strokeColor = borderColor.cgColor
        borderLayer.fillColor = UIColor.clear.cgColor
        borderLayer.frame = self.bounds
        self.layer.addSublayer(borderLayer)
    

这样使用,

button.backgroundColor = UIColor.brown
button.roundCorners([.allCorners], radius: 30.0, borderColor: UIColor.white, borderWidth: 10.0)

这将显示这样的输出,

上图包含带有白色边框颜色的按钮。

这将是您应用程序中所有按钮的通用解决方案。

如有任何疑问,请告诉我。

【讨论】:

已应用圆角。但是按钮没有显示 按钮怎么没显示?你能详细说明一下吗 private let connectButton: UIButton = let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.setTitle("Test", for: .normal) button.setTitleColor(.white, for: .normal ) button.titleLabel?.font = .systemFont(ofSize: 15, weight: .bold) button.backgroundColor = UIColor.brown button.roundCorners(.allCorners, radius: 30.0, borderColor: UIColor.white, borderWidth: 5.0) 返回按钮() 不使用 xib,情节提要。它是用代码编写的。创建按钮的地方是tableViewCell。我一定会因为你的努力而成功。 :D 子类 UIButton 并在覆盖 func layoutSubviews() 时调用此方法【参考方案2】:

shadowOpacity 设置为零应该可以解决您的问题。

button.layer.shadowOpacity = 0.0;

【讨论】:

我没有设置阴影选项。我尝试了清晰的颜色,但失败了。【参考方案3】:

您必须裁剪图层的边界。

button.layer.masksToBounds = true

【讨论】:

【参考方案4】:

我知道为什么按钮周围有一条线,我以前遇到过。实际上这条线是边框和背景之间的间隙,button.layer.border 没有正确绘制。可以尝试自己画个边框,盖在按钮上。

【讨论】:

【参考方案5】:

你必须剪裁边界并添加一个空白标题

 button.clipsToBounds = true
 button.setTitle("  ", for: .normal)

【讨论】:

以上是关于iOS - 如何删除 UIButton 边框颜色?的主要内容,如果未能解决你的问题,请参考以下文章

具有自定义边框颜色的 UIButton,iPhone

在 Swift 3 中突出显示(或点击)按钮时如何更改 UIButton 边框颜色?

iOS:自定义按钮(UIButton 的子类) - 无法更改边框属性

两个 UIButton 形成一个具有渐变颜色,另一个具有边框和圆角

以编程方式将渐变边框颜色应用于 UIButton

CGContextClearRect 导致背景颜色为黑色