2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Swift】 ボタン押下時に画面にViewを追加する

Posted at

####はじめに
会社で提供してるWebサービス専用のタブブラウザを作れないか、というコトで、実現性評価を何段階かに分けてやってるうちの1つ。
ボタン押下時にUIViewを画面に追加する。

####開発環境
端末:MacBook Pro/MacOS 10.14.5(Mojave)
Xcode:10.2.1
Swift:5

####やったこと
ボタン押下時に、画面のランダムな場所に10px*10pxのUIViewを表示。
 →ボタンを押下するたびにどんどんUIViewを追加していく。

####実装
#####画面イメージ

起動時
ボタン連打
※色と場所がランダムに設定されたUIViewがボタンを押すたびに画面に配置されていく。

#####ソースサンプル

ViewController.swift
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var btnCreateView: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        btnCreateView.center = view.center
    }

    @IBAction func createView(_ sender: Any) {
        let testView: UIView = UIView()
        
        let viewWidth = UIScreen.main.bounds.width
        let viewHeight = UIScreen.main.bounds.height
        
        let randX = CGFloat(Int.random(in: 0 ... Int(viewWidth)))
        let randY = CGFloat(Int.random(in: 0 ... Int(viewHeight)))
        
        let randRed = CGFloat(Int.random(in: 0 ... 255))
        let randGreen = CGFloat(Int.random(in: 0 ... 255))
        let randBlue = CGFloat(Int.random(in: 0 ... 255))
        
        testView.backgroundColor = .init(red: randRed/255,
                                         green: randGreen/255,
                                         blue: randBlue/255,
                                         alpha: 1)
        
        testView.frame = CGRect.init(x: randX, y: randY, width: 10, height: 10)
        
        view.addSubview(testView)
    }
}

####感想等
実現性評価というか、まぁこうなるだろうな〜ってイメージを順当に形にした感じです。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?