在swift 2中为button创build可扩展的三行菜单导航图标

我怎样才能让我的button可扩展? 以编程方式,使用vector或别的东西? 这只是一个典型的带有三重线的导航图标。 有没有一种简单的方法来创build清晰,可缩放的图标,而不使用图像?

是的,您可以使用Core Graphics创build图标。 请按照这些简单的4个步骤来绘制3个酒吧button图标。

1)添加UIButton到你的故事板并放置它。 在这里输入图像说明

2)创buildCocoa类的基类UIButton的名字就像是“NavButton”,粘贴下面的代码 在这里输入图像说明

 import UIKit class NavButton: UIButton { override func drawRect(rect: CGRect) { // thickness of your line let lineThick:CGFloat = 1.0 // length of your line relative to your button let lineLenght:CGFloat = min(bounds.width, bounds.height) * 0.8 // color of your line let lineColor: UIColor = UIColor.whiteColor() // this will add small padding from button border to your first line and other lines let marginGap: CGFloat = 5.0 // we need three line for line in 0...2 { // create path let linePath = UIBezierPath() linePath.lineWidth = lineThick //start point of line linePath.moveToPoint(CGPoint( x: bounds.width/2 - lineLenght/2, y: 6.0 * CGFloat(line) + marginGap )) //end point of line linePath.addLineToPoint(CGPoint( x: bounds.width/2 + lineLenght/2, y: 6.0 * CGFloat(line) + marginGap )) //set line color lineColor.setStroke() //draw the line linePath.stroke() } } } 

3)从Identity Inspector> Custom Class> Class字段中将NavButton类分配给您的UIButton 在这里输入图像说明

4)从Attribute Inspector> Default Title(第四个)中删除默认标题 在这里输入图像说明

完成,现在build立并运行你可以看到你的button与酒吧 在这里输入图像说明

更新@ KamaalABOOTHALIB对Swift 3 的回应 :

 import UIKit class NavButton: UIButton { override func draw(_ rect: CGRect) { // thickness of your line let lineThick:CGFloat = 1.0 // length of your line relative to your button let lineLength:CGFloat = min(bounds.width, bounds.height) * 0.8 // color of your line let lineColor: UIColor = UIColor.black // this will add small padding from button border to your first line and other lines let marginGap: CGFloat = 5.0 // we need three line for line in 0...2 { // create path let linePath = UIBezierPath() linePath.lineWidth = lineThick //start point of line linePath.move(to: CGPoint( x: bounds.width/2 - lineLength/2, y: 6.0 * CGFloat(line) + marginGap )) //end point of line linePath.addLine(to: CGPoint( x: bounds.width/2 + lineLength/2, y: 6.0 * CGFloat(line) + marginGap )) //set line color lineColor.setStroke() //draw the line linePath.stroke() } }