2016-02-25 83 views
2

我在UIView上創建了一個擴展,這樣我就可以輕鬆創建圓視圖,而無需在每個自定義組件中編寫代碼。我的代碼看起來:Swift:生成一個圓UIView給出了一個形狀的鑽石

extension UIView { 
    func createCircleView(targetView: UIView) { 
     let square = CGSize(width: min(targetView.frame.width, targetView.frame.height), height: min(targetView.frame.width, targetView.frame.height)) 
     targetView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: square) 
     targetView.layer.cornerRadius = square.width/2.0 
    } 
} 

財產square是要始終計算基礎上,從目標視圖widthheight最小的屬性完全平方的目的,這將停止矩形從試圖成爲正方形,作爲顯然不會產生一個圓圈。

在我的自定義組件,我把這種方法用:

// machineCircle is a child view of my cell 
@IBOutlet weak var machineCircle: UIView! 

// Whenever data is set, update the cell with an observer 
var machineData: MachineData? { 
    didSet { 
     createCircleView(machineCircle) 
    } 
} 

我遇到的問題是,我的圓圈呈現到這樣的畫面:

enter image description here

調試時,我檢查了方形變量,它始終打印出width: 95, height: 95,這會讓我相信每次都應該呈現完美的圓形。

爲什麼我看到這些奇怪的形狀?

UPDATE我發現爲什麼完美的圈子沒有形成,但我不知道如何去做。

以我的故事板設置我machineCircle視圖的默認大小是95x95,但是當我的視圖負載時,收集細胞寬度和高度與該方法動態計算:

override func viewDidLoad() { 
    super.viewDidLoad() 

    let width = CGRectGetWidth(collectionView!.frame)/3 
    let layout = collectionViewLayout as! UICollectionViewFlowLayout 
    layout.itemSize = CGSize(width: width, height: width + width/2) 
} 

此調整大小的收集查看單元格,以便它們可以在屏幕上以3列爲單位進行匹配,但似乎並未改變內部機器圓視圖的基本比例。 machineCircle視圖仍然保留95x95的大小,但似乎在視圖內縮小,導致效果被引起(這就是我迄今爲止所觀察到的)。有任何想法嗎?

+0

當您更改圓的大小時,您需要再次設置圓角半徑 – dan

+0

通過做圓角半徑來創建圓是愚蠢的。如果你想要一個圓圈,做一個_circle_! – matt

+0

你不能在viewDidLoad中信任你的視圖的大小/位置。視圖控制器的大小仍然與它們在XIB/storyboard中聲明的大小相同。 (它們沒有爲當前設備調整大小/定位。)您需要將計算代碼放在viewWillAppear中。(雖然馬特說,如果你想畫一個圓,爲什麼不畫一個圓。) –

回答

0

接受Matt的建議,我創建了一個方法來使用CALayers在UIView中繪製一個圓。

對於任何誰有興趣,這裏是我的實現:

func drawCircleInView(parentView: UIView, targetView: UIView, color: UIColor, diameter: CGFloat) 
{ 
    let square = CGSize(width: min(parentView.bounds.width, parentView.bounds.height), height: min(parentView.bounds.width, parentView.bounds.height)) 
    let center = CGPointMake(square.width/2 - diameter, square.height/2 - diameter) 

    let circlePath = UIBezierPath(arcCenter: center, radius: CGFloat(diameter), startAngle: CGFloat(0), endAngle: CGFloat(M_PI * 2), clockwise: true) 
    let shapeLayer = CAShapeLayer() 
    print(targetView.center) 
    shapeLayer.path = circlePath.CGPath 

    shapeLayer.fillColor = color.CGColor 
    shapeLayer.strokeColor = color.CGColor 
    shapeLayer.lineWidth = 1.0 

    targetView.backgroundColor = UIColor.clearColor() 
    targetView.layer.addSublayer(shapeLayer) 
} 

,它被稱爲有:

drawCircleInView(self, machineCircle, color: UIColor.redColor(), radius: 30) 

下面是結果:

enter image description here

的後面的白色框僅用於演示目的,它顯示了父母vi如果圈出來,這將在生產中被設置爲透明。