【Swift】スクロール画面に大量のUIButtonを等間隔で配置
完成図
解説
「手順」
- ScrollViewを設置
- UIViewを生成
- UIButtonを生成
- UIButton.frameを設定
- UIButton.tagを設定
- UIButtonに文字や処理を設定
- UIViewに設置
- 3~7をループ
- ScrollViewにUIViewを設置
- ScrollView.contenSizeとUIView.bounds.sizeを同じにする
「ポイント」
- for文のループ内にある変数iにかける数値がUIButton同士の幅となる
- 横ならx座標を増加させ、縦ならy座標を増加させればいい
ストーリーボード
ソースコード
import UIKit class ViewController: UIViewController { @IBOutlet weak var scrollView1: UIScrollView! @IBOutlet weak var scrollView2: UIScrollView! var vc1 = UIView() var vc2 = UIView() override func viewDidLoad() { super.viewDidLoad() //ScrollView上に要素を配置 verticalScroll() horizontalScroll() } //横スクロール func horizontalScroll() { //vcのframe vc1.frame = CGRect(x: 0, y: 0, width: scrollView1.frame.size.width * 2, height: scrollView1.frame.size.height) //上部のスクロールビューに多数のボタンを配置 for i in 0...6 { let button = UIButton() //サイズ button.frame = CGRect(x: (i*100), y: 30, width: 80, height: 55) //タグ button.tag = i //buttonに文字を挿入 setTitleForButton(tag: button.tag, button: button) //button.titleの色 button.setTitleColor(.white, for: .normal) button.layer.borderWidth = 1 //vcに載せる vc1.addSubview(button) } //スクロールビューにvcを配置 scrollView1.addSubview(vc1) //scrollViewのコンテンツサイズをvc1のサイズにする scrollView1.contentSize = vc1.bounds.size } //縦スクロール func verticalScroll() { //vcのframe vc2.frame = CGRect(x: 0, y: 0, width: scrollView2.frame.size.width, height: scrollView2.frame.size.height * 2) //上部のスクロールビューに多数のボタンを配置 for i in 0...6 { let button = UIButton() //サイズ button.frame = CGRect(x: 120, y: (i*100), width: 80, height: 55) //タグ button.tag = i //buttonに文字を挿入 setTitleForButton(tag: button.tag, button: button) //button.titleの色 button.setTitleColor(.white, for: .normal) button.layer.borderWidth = 1 //vcに載せる vc2.addSubview(button) } //スクロールビューにvcを配置 scrollView2.addSubview(vc2) scrollView2.contentSize = vc2.bounds.size } //スクロールビューのボタンに文字を入れる func setTitleForButton(tag:Int, button:UIButton){ switch tag { case 0: button.setTitle("最新", for: .normal) case 1: button.setTitle("人気", for: .normal) case 2: button.setTitle("フォロー", for: .normal) case 3: button.setTitle("文学", for: .normal) case 4: button.setTitle("社会", for: .normal) case 5: button.setTitle("科学", for: .normal) case 6: button.setTitle("ビジネス", for: .normal) default: break } } }