このようなリングに円形のボタンをプロットしようとしています。
私は6つのUIボタンを持っており、それらはすべて360度の角半径を持っています。私がSwiftでやろうとしているのは、上の画像のように中央のボタン/ポイントの周りに均等にプロットすることです。各円は、隣接する円から等間隔に配置されます。この機能を実現するための最良の方法は何ですか?ベジェ曲線を作成してから、数学を使用してその曲線の周りにボタンをプロットする必要がありますか、それとも別の方法を提案しますか?
ちなみに、私はいかなる種類の放射状メニューも探していません。アニメーションは必要ありません。既存のUIボタンを上記の形式でプロットしようとしています。
ありがとう!
数学(三角法)を使用して中央のボタンからの水平方向と垂直方向のオフセットを計算してから、レイアウトアンカーを使用してボタンを配置することをお勧めします。
これは自己完結型の例です:
class ViewController: UIViewController {
func createButton(size: CGFloat) -> UIButton {
let button = UIButton(type: .custom)
button.backgroundColor = .red
button.translatesAutoresizingMaskIntoConstraints = false
button.widthAnchor.constraint(equalToConstant: size).isActive = true
button.heightAnchor.constraint(equalToConstant: size).isActive = true
button.layer.cornerRadius = size / 2
return button
}
func setUpButtons(count: Int, around center: UIView, radius: CGFloat) {
// compute angular separation of each button
let degrees = 360 / CGFloat(count)
for i in 0 ..< count {
let button = createButton(size: 50)
self.view.addSubview(button)
// use trig to compute offsets from center button
let hOffset = radius * cos(CGFloat(i) * degrees * .pi / 180)
let vOffset = radius * sin(CGFloat(i) * degrees * .pi / 180)
// set new button's center relative to the center button's
// center using centerX and centerY anchors and offsets
button.centerXAnchor.constraint(equalTo: center.centerXAnchor, constant: hOffset).isActive = true
button.centerYAnchor.constraint(equalTo: center.centerYAnchor, constant: vOffset).isActive = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
let centerButton = createButton(size: 50)
self.view.addSubview(centerButton)
// use anchors to place center button in the center of the screen
centerButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
centerButton.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
setUpButtons(count: 6, around: centerButton, radius: 100)
}
}
ノート:
中央のボタンが必要ない場合は、周りにボタンを設定するだけself.view
です。
setupButtons(count: 6, around: self.view, radius: 100)
または任意のポイントの周り:
let point = CGPoint(x: 180, y: 300)
let centerView = UIView(frame: CGRect(origin: point, size: CGSize.zero))
self.view.addSubview(centerView)
setUpButtons(count: 6, around: centerView, radius: 140)
UIView
ポイントの代わりにを中心として使用すると、動的に移動できUIView
、ボタンが追従するため、より柔軟になります。ここでは、シミュレーターで実行されています。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加