2016-10-06 4 views
2

ボタンのフレームに基づいてcornerRadiusプロパティを計算する方法丸い角を作成するにはボタンフレームに応じてcornerRadiusを適切に計算する方法

各ボタン項目のコーナーcornerRadiusを毎回再定義したくありません。

UIButtonの内線番号を作成します。

extension UIButton { 

    func setRoundedCorners(){ 
     self.layer.cornerRadius = 10 
     self.layer.borderWidth = 1 
    } 

} 

と私はあまりにもダイナミックにcornerRadius私はこの機能を使用するたびに計算する方法を知っていただきたいと思います。

さまざまなボタンサイズで.cornerRadiusを計算する関数を見つけるための主な問題です。以下の例は小さな違いを示しています。

例:

コーナー半径が10:

enter image description here

コーナー半径が15:

enter image description here

それが適切な値を計算する関数を求めることができますコーナーの半径を与えるだろうか?

+0

あなたは私のUI私を与える必要があるボタンのどのような種類あなたにコードを与えるでしょう。 –

+0

フレームに基づいて異なるボタンの適切なコーナー半径を計算するフレキシブルな機能を得るための主な考え方 –

+0

円形または丸みのあるコーナーのような形状はどんな種類ですか? –

答えて

1

そのフレーム

に基づいて異なるボタンのための適切 角の半径を計算する柔軟な機能を取得するための主なアイデア、私はそれはあなたが引数として渡すものをあなた次第だと思う:

extension UIButton { 
    func setRoundedCorners(ratio: Double?) { 
     if let r = ratio { 
      self.layer.cornerRadius = self.frame.size.width*r // for specific corner ratio        
     } else { 

      // circle 
      // i would put a condition, as width and height differ: 
      if(self.frame.size.width == self.frame.size.height) { 
       self.layer.cornerRadius = self.frame.size.width/2 // for circles 
      } else { 
       // 
      } 
     } 
     self.layer.borderWidth = 1 
    } 
} 

使用

let button = UIButton() 
button.setRoundedCorners(ratio: 0.25) // shape with rounded corners 
button.setRoundedCorners() // circle 
+0

ボタンのフレームに基づいてこの比率を計算する関数を書くことは可能ですか? –

+0

私はそれを既に好きでした。 – pedrouan

+1

関数でコーナーの半径を誤って計算する問題。 –

0

btnarrival BTN2、BTN1このコードを試してみてください、私のUIButtonです。

btn1.SetCornerRadiusbutton() 
btn2.SetCornerRadiusbutton() 
btnarrival.SetCornerRadiusbutton() 


extension UIButton{ 
    func setCornerRadiusbutton() { 
     self.layer.cornerRadius = self.frame.size.height/2 
     self.clipsToBounds = true 

    } 
} 

Did u want button look like this then try this my code..

+0

私のこのコードでは何が問題ですか?誰が私に投票してくださいそれを明確にしてください。 –

+1

私の視点からはすべてが大丈夫です –

+0

私のコードでは、より少ないcornerRadiusを与えたい場合は、3を単に分割して、cornerRadiusを減らしてください。 –

1

私は同じことを探していると自分自身に非常に明確かつ簡単な解決策を見つけました。 UIViewの拡張機能であるため、ボタンではなく複数のオブジェクトで使用できます。

extension UIView{ 
    func cornerCalculation(r: CGFloat) { 
     self.layer.cornerRadius = self.frame.height/2 * r 
    } 
} 

してからちょうど呼び出す:

button.cornerCalculation(r: 1) 

rは0(シャープなエッジ)と1(completley丸いエッジ)の間の任意の数になります

関連する問題