2017-02-10 81 views
1
myLabel.layer.borderWidth = 0.5 
myLabel.layer.borderColor = UIColor.green.cgColor 

這就是繪製邊框的簡單答案。然而,問題是我需要僅將邊界繪製到右側和底部。我還需要另一個標籤來在右上角繪製邊框。我怎樣才能把邊界畫到特定的邊,而不是全部四邊?圍繞textview或標籤快速繪製邊框

+0

的可能的複製[CALayer的:添加邊框僅在一側(http://stackoverflow.com/questions/7022656/calayer-add-a-border -only-AT-一側) –

回答

1

添加形狀圖層,繪製該層中的線。請注意,圖層不參與自動佈局,因此您需要將代碼放入viewDidLayoutSubviews或子類uilabel中,然後在佈局子視圖中執行此操作。下面是使用的UILabel子類的遊樂場例如:

import PlaygroundSupport 
    import UIKit 
    class L: UILabel { 
     var strokeColor = UIColor.blue 
     var strokeWidth = CGFloat(0.5) 
     private lazy var labelBorderLayer:CAShapeLayer = { 
      let shapeLayer = CAShapeLayer() 
      self.layer.addSublayer(shapeLayer) 
      return shapeLayer 
     }() 
     override func layoutSubviews() { 
      super.layoutSubviews() 
      let path = CGMutablePath() 
      path.move(to: CGPoint(x: 0, y: bounds.size.height)) 
      path.addLine(to: CGPoint(x: bounds.size.width, y: bounds.size.height)) 
      path.addLine(to: CGPoint(x: bounds.size.width, y: 0)) 
      labelBorderLayer.path = path 
      labelBorderLayer.strokeColor = strokeColor.cgColor 
      labelBorderLayer.lineWidth = strokeWidth 
      labelBorderLayer.fillColor = UIColor.clear.cgColor 
     } 
    } 

    let v = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) 
    let l = L(frame: v.frame.insetBy(dx: 50, dy: 80)) 
    v.addSubview(l) 
    l.textColor = .white 
    l.textAlignment = .center 
    l.text = "gjgkjgjgjgj" 
    v.backgroundColor = .red 
    PlaygroundPage.current.liveView = v 
0

我不知道你是否可以用實際的標籤邊框做到這一點。但是,你可以做類似於這個

public enum UIButtonBorderSide { 
     case Top, Bottom, Left, Right 
    } 

extension UIButton { 
public func addBorder(side: UIButtonBorderSide, color: UIColor, width: CGFloat) { 
    let border = CALayer() 
    border.backgroundColor = color.CGColor 

    switch side { 
    case .Top: 
     border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: width) 
    case .Bottom: 
     border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: width) 
    case .Left: 
     border.frame = CGRect(x: 0, y: 0, width: width, height: self.frame.size.height) 
    case .Right: 
     border.frame = CGRect(x: self.frame.size.width - width, y: 0, width: width, height: self.frame.size.height) 
    } 

    self.layer.addSublayer(border) 
} 
} 

這就是UIButton,但你可以很容易地適應它。

來源:https://gist.github.com/Isuru-Nanayakkara/496d5713e61125bddcf5

希望這有助於