2016-08-06 5 views
2

私は、3つのUIButtonsのビューコントローラーを持ち、それぞれ同じY位置を持ち、水平方向に20px離れています。ボタンが選択されているとき、ボタンの下に線を描きたいと思います。私はアンダーライン属性を追加しようとしましたが、ラインは実際にはカスタマイズできません。 SectionViewという名前のUIViewのサブクラスに含まれるUIImageViewの上にボタンがあります。私のビューコントローラでUIButtonの下線はビューの内側に隠されています

私はボタンが押されたときに呼び出される次の関数ています、私は次のように私のUIViewサブクラスで

@IBOutlet weak var sectionView: SectionView! 

func sectionButtonPressed(sender: UIButton) { 
    self.sectionView.selectedButton = sender 
    self.sectionView.setNeedsDisplay() 
} 

を持っている:

class SectionView: UIView { 

    var selectedButton: UIButton? 

    override func drawRect(rect: CGRect) { 

     let linePath = UIBezierPath() 

     linePath.moveToPoint(CGPoint(x:(self.selectedButton?.frame.origin.x)! - 3, y: (self.selectedButton?.frame.origin.y)! + 35)) 
     linePath.addLineToPoint(CGPoint(x: (self.selectedButton?.frame.origin.x)! + (self.selectedButton?.frame.width)! + 3, y: (self.selectedButton?.frame.origin.y)! + 35)) 
     linePath.closePath() 
     UIColor.purpleColor().set() 
     linePath.stroke() 
     linePath.fill() 
    } 
} 

は私が得ることができますUIButtonとUIImageViewの下にある、私が望む位置と長さを描画する線。上に表示するにはどうすればいいですか?

答えて

0

私はそれを変更する必要がありました。ベジェパスを使用する代わりに、UIViewを作成して他のビューの上に配置しました。

func sectionButtonPressed(sender: UIButton) { 
    let lineView = createView(sender) 
    self.sectionView.addSubview(lineView) 
} 

func createView(sender:UIButton) -> UIView { 

    let customView = UIView(frame: CGRect(x: sender.frame.origin.x, y: sender.frame.origin.y + 12, width: sender.frame.width, height: 2.0)) 
    customView.backgroundColor = UIColor.purpleColor() 
    return customView 

} 

私のボタンがUIView内に含まれているUIImageViewの上にある、覚えておいてください。ラインビューをサブビューとして画像ビューに追加しようとすると、そのラインはボタンのx原点と並ばなくなります。だから代わりに私はUIViewにサブビューとしてラインビューを追加し、それが正しく見えた。

0

CALayerを使用して線を描くことができます。ボタンアクションに次のコードを追加してください。これが役立ちます。

@IBAction func sectionButtonPressed(sender: AnyObject) { 
    let border = CALayer() 
    border.borderColor = UIColor.purpleColor().CGColor 
    border.frame = CGRect(x: 0, y: sender.frame.size.height - 2, 
          width: sender.frame.size.width, height: 2) 
    border.borderWidth = 2.0 
    sender.layer.addSublayer(border) 
    sender.layer.masksToBounds = true 
} 

結果:

enter image description here

+0

'のCALayerを使用するメリットは何ですか'vs a' UIView' – Brosef

+0

UIViewとはちょっと変わり、簡単な方法です – Gokul

0
func addLine(button:UIButton)// pass button object as a argument 
{ 
    let length = button.bounds.width 
    let x = button.bounds.origin.x 
    let y = button.bounds.origin.y + button.bounds.height - 5 
    let path = UIBezierPath() 
    path.move(to: CGPoint(x: x, y: y)) 
    path.addLine(to: CGPoint(x: x + length , y:y)) 
    //design path in layer 
    let lineLayer = CAShapeLayer() 
    lineLayer.path = path.cgPath 
    lineLayer.strokeColor = UIColor.red.cgColor 
    lineLayer.lineWidth = 1.0 
    lineLayer.fillColor = UIColor.clear.cgColor 
    button.layer.insertSublayer(lineLayer, at: 0) 
}` 

//このコードは(UIBezierPathとレイヤーを使用して)あなたのボタンの下に1行が作成されます

関連する問題