【问题标题】:How to create dashed uibutton如何创建虚线 uibutton
【发布时间】:2017-11-10 08:42:24
【问题描述】:

在我的项目中,我想创建如下图所示的虚线 uibutton。有没有办法改变虚线颜色?

【问题讨论】:

  • 最简单的解决方案可能是创建一个图像 - 使用文字和您想要的任何颜色的虚线,并将其设置为 UIButton.image。如果您需要它是动态的,您可以以编程方式创建图像,并在运行时设置它

标签: ios objective-c swift3 uibutton storyboard


【解决方案1】:

正如 cmets 和答案所建议的那样,您可以使用图像,但我们可以改用 CAShapeLayer 并控制各个方面。

可能是这样的:

class DashedButton: UIButton {

    var dashedLine: CAShapeLayer!

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    func setup() {
        dashedLine             = CAShapeLayer()
        dashedLine.strokeColor = UIColor.white.cgColor
        dashedLine.lineWidth   = 4
        layer.addSublayer(dashedLine)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        let path = UIBezierPath()
        path.move(to: CGPoint(x: bounds.minX, y: bounds.maxY))
        path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY))
        dashedLine.lineDashPattern = [12, 7]
        dashedLine.path = path.cgPath
    }

}

可以像这样使用(请注意,我在这里使用框架,因为我在操场上对其进行了测试,更常见的用途是通过故事板/xib 文件进行实例化):

let button = DashedButton(frame: CGRect(x: 0, y: 0, width: 100, height: 30))

button.setTitle("Forgot Password?", for: .normal)
button.dashedLine.strokeColor = UIColor.orange.cgColor
button.sizeToFit()

产生这个:


旁注:此示例是帮助您快速入门的方法。例如,您可以添加自定义设置器来处理线条着色和图案。另请注意,我通过指定填充以破折号而不是间隙结尾的按钮的整个宽度的模式来“作弊”,而不是动态计算长度(留给对此解决方案感兴趣的任何人的练习:))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多