[Swift] Create UIButton class in code

Create UIButton class

Buttons are of the UIButton class, so you can create buttons on your instance.

Preparation

Download the background image of the button appropriately. ダウンロード.png

Put the above image in the Assets folder. You are now ready.

Try


import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //Make a button
        let okButton=UIButton()
        //Area and button position
        okButton.frame=CGRect(x:100,y:100,width: 120,height: 120)
        //background image
        let bkgImage=UIImage(named: "maru.png ")
        okButton.setBackgroundImage(bkgImage, for: .normal)
        
        view.addSubview(okButton)
    }
}

First, store an instance of UIButton in okButton. Then, determine the position and size of the button with the CGRect type. Load the background image as UIImage type and pass the value to the argument of setBackgroundImage method.

Finally, pass an okButton as an argument to the view.addSubView method. This is the method for displaying a button in view.

Recommended Posts

[Swift] Create UIButton class in code
Implement Swift UITextField in code
Create Master Detail in Swift UI
Create an HTML/XML generator in Swift (dynamicMemberLookup)
Class in Ruby
Compare objects in Swift
How to implement UICollectionView in Swift with code only
Division becomes 0 in Swift
Create UnsafeMutablePointer <UnsafeMutablePointer <Int8>?>! In Swift for C char ** hoge
Implement CustomView in code
Create JSON in Java
Multidimensional array in Swift
NullpointException in injecting class
Create QR code for Google Authenticator using ZXing in Java
[Swift5] How to avoid applying dark mode (dark appearance) in code
[Beginner] Implement NavigationBar in code
Write class inheritance in Ruby
Code entry method in Qiita
Create hyperlinks in Java PowerPoint
Photo library in Swift UI
Create a VS Code Plugin.
code smell refactoring [lazy class]
Create Azure Functions in Java
Java in Visual Studio Code
Write Java8-like code in Java8
I can't create a Java class with a specific name in IntelliJ