2016-06-12 88 views
4

我一直在試圖使單元格中的UIButton成爲一個完美的圓。不幸的是,圓圈是基於背景圖片而不是UIButton框架形成的。如何使UIButton成爲一個圓圈?

的代碼我創建圈子:

cell.StoryViewButton.setImage(image, forState: .Normal) 
cell.StoryViewButton.frame = CGRectMake(50, 8, 100, 100) 
cell.StoryViewButton.layer.masksToBounds = false 
cell.StoryViewButton.layer.cornerRadius = cell.StoryViewButton.frame.width/2 
cell.StoryViewButton.clipsToBounds = true 

輸出看起來是這樣的:Output Images for each cell

我能做些什麼來獲得我想要的完美的圓形按鈕框架?

+0

使用Autolayout?那麼設置框架不起作用。 – HDT

+0

@HDT是的,我使用Autolayout,我應該使用它嗎? –

+0

這取決於你當前的實現,但你仍然可以使用Autolayout,但是,不要設置框架,而是使用約束來平均地設置視圖的寬度和高度。 – HDT

回答

8

嘗試是這樣的

cell.StoryViewButton.layer.masksToBounds = true 
cell.StoryViewButton.layer.cornerRadius = cell.StoryViewButton.frame.width/2 

如果你需要創建的視圖,你必須masksToBounds設置爲true了一圈,沒有設置clipsToBounds

希望這會幫助你。

+0

Thx it work,thx @Nirav D – AliasCocoa

0

有工作代碼。我測試它。希望能幫助到你。 我不知道爲什麼,但我檢查通過更改框架的高度和寬度在這裏「CGRectMake(50,8,120,120)」框架的高度和寬度以及按鈕的高度和寬度應該是同樣得到完美的圓圈。

cell.StoryViewButton.setImage(image, forState: .Normal) 
cell.StoryViewButton.frame = CGRectMake(50, 8, 120, 120) 
cell.StoryViewButton.layer.cornerRadius = self.btn.frame.width/2; 
cell.StoryViewButton.layer.masksToBounds = true 

希望它有幫助。

1

斯威夫特4

您可以應用下面的函數任何視圖,包括按鈕。

func makeViewCircular(view: UIView) { 
    view.layer.cornerRadius = view.bounds.size.width/2.0 
    view.clipsToBounds = true 
} 

太好了。

這對我來說並不適用,因爲我在viewDidLoad中應用它。在這一點上,約束仍在玩你的按鈕的大小和角落半徑應用於一個按鈕,它認爲是兩倍的大小,導致你有奇怪的形狀。要將正確的值應用於正確的測量,請將代碼放入override func viewDidLayoutSubviews()

我知道這可能是我個人過程中的一個更具體的情況,但我相信它會幫助某人。