2017-02-18 36 views
-2

如何在表格單元格上創建圓形圖像?例如:如何在UITableViewCell中創建一個圓形狀?

enter image description here

這是我們與箭頭指向故事板,我們試圖繪製一個圓,當我們想突出顯示該行:

enter image description here


更新

決定使用自定義字體d相關Swift library。正如Leo指出,當您可以使用圖像(或字體)時,生成一個圓圈是矯枉過正的。是添加新的標籤,並設置字體/圖標一樣容易:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    .. 
    if doHighlight { 
     cell.statusLabel.setFAIcon(icon: .FACircle, iconSize: 6) 
    } 
    .. 

回答

1

最高效的方法是添加一個圓形的圖像。設置cornerRadius可以正常工作,但這是一個性能問題,它對於一個簡單的彩色圓圈來說是一種矯枉過正。

0

添加一個UIView實例,並設置其layer.cornerRadius到一半的寬度/高度。

0

如果高度&寬度= 50

View.clipsToBounds = true 
    View.layer.cornerRadius= View.frame.size.width/2 
0
class CircularImageView: UIImageView { 
override func layoutSubviews() { 
    super.layoutSubviews() 

    let radius: CGFloat = self.bounds.size.width/2.0 
    self.layer.cornerRadius = radius 
    self.clipsToBounds = true 
} } 

也可以使一個圓形圖像視圖,其是的UIImageView的子類,所以,可以直接將其設置爲的UIImageView ...

1

你可以作出一個觀點,增加一個圓圈CAShapeLayer

@IBDesignable class CircleView: UIView { 

    @IBInspectable public var fillColor: UIColor = #colorLiteral(red: 0, green: 0, blue: 1, alpha: 1) { didSet { shapeLayer.fillColor = fillColor.cgColor } } 
    @IBInspectable public var strokeColor: UIColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0) { didSet { shapeLayer.strokeColor = strokeColor.cgColor } } 
    @IBInspectable public var lineWidth: CGFloat = 0 { didSet { setNeedsLayout() } } 

    lazy private var shapeLayer: CAShapeLayer = { 
     let _shapeLayer = CAShapeLayer() 
     _shapeLayer.fillColor = self.fillColor.cgColor 
     _shapeLayer.strokeColor = self.strokeColor.cgColor 
     self.layer.insertSublayer(_shapeLayer, at: 0) 
     return _shapeLayer 
    }() 

    override func layoutSubviews() { 
     super.layoutSubviews() 

     let center = CGPoint(x: bounds.midX, y: bounds.midY) 
     let radius = (min(bounds.size.width, bounds.size.height) - lineWidth)/2 
     shapeLayer.path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true).cgPath 
     shapeLayer.lineWidth = lineWidth 
    } 
} 

N ote,即@IBDesignable,因此您可以在Interface Builder中使用它。只需創建一個單獨的目標(「文件」 - 「新建」 - 「目標...」)並選擇「Cocoa Touch Framework」並給它一個合適的名稱(例如,如果你的應用程序是「Foo」 「FooKit」)。接着上面的UIView子類添加到該框架,你可以參考這個類IB(剛加入UIView對象並改變其基類CircleView):

circle in IB

相關問題