[Swift] How to fix Label in UIPickerView

Introduction

It is a method to fix Label such as "min" "sec" below in PickerView. It doesn't move even if you slide it up and down! I couldn't do this because I wanted to do it, but I'll introduce it because the mystery has been solved.

[reference] https://medium.com/@luisfmachado/uipickerview-fixed-labels-66f947ded0a8

スクリーンショット 2020-12-30 13.54.42.png

Method

① Add a method to UIPickerViewClass with extension

Write the following code.

extension UIPickerView {
    func setPickerLabels(labels: [Int:UILabel]) { // [component number:label]
        
        let fontSize:CGFloat = 20
        let labelWidth:CGFloat = self.frame.size.width / CGFloat(self.numberOfComponents)
        let x:CGFloat = self.frame.origin.x
        let y:CGFloat = (self.frame.size.height / 2) - (fontSize / 2)

        for i in 0...self.numberOfComponents {
            
            if let label = labels[i] {
                label.frame = CGRect(x: labelWidth * CGFloat(i), y: y, width: labelWidth, height: fontSize)
                label.font = UIFont.systemFont(ofSize: fontSize, weight: .light)
                label.backgroundColor = .clear
                label.textAlignment = NSTextAlignment.center
                self.addSubview(label)
            }
        }
    }
}

② Used in titleForRow

Next, actually use the method written in extension earlier. Below is all the code needed to implement PickerView, but the actual method usage is at "titleForRow". The place to actually use is marked.

class SettingTimerViewController: UIViewController {
    
    var secIntArray = [Int](0...59)
    var minIntArray = [Int](1...10)
    
    let settingTimerPickerView = UIPickerView()
    let setTimeButton = UIButton()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
       setUpView()
        
    }
    
    func setUpView() {
        //PickerView
        settingTimerPickerView.frame.size.width = 240
        settingTimerPickerView.frame.size.height = self.view.frame.size.height/3
        settingTimerPickerView.layer.position = CGPoint(x: self.view.frame.width/2, y:self.view.frame.size.height/3)
        self.view.addSubview(settingTimerPickerView)
        settingTimerPickerView.delegate = self
        settingTimerPickerView.dataSource = self
    }
}

extension SettingTimerViewController: UIPickerViewDelegate, UIPickerViewDataSource {
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 4
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        switch component {
        case 0:
            return minIntArray.count
        case 1:
            return 1
        case 2:
            return secIntArray.count
        case 3:
            return 1
        default:
            return 0
        }
    
    }
    
  //Use the method in this.
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        switch component {
        case 0:
            return String(minIntArray[row])
        case 1:
            let min = UILabel() 
            min.text = "min"  //Enter the Label name you want to display instead of min.
            settingTimerPickerView.setPickerLabels(labels: [1: min]) //It is okay if you enter the same number as the case for 1.
Enter the number of.
            return ""
        case 2:
            return String(secIntArray[row])
        case 3:
            let sec = UILabel()
            sec.text = "sec" //Enter the Label name you want to display instead of sec.
            settingTimerPickerView.setPickerLabels(labels: [3: sec]) //It is okay if you enter the same number as the case for 3.
Enter the number of.
            return ""
        default:
            return "error"
        }
    }
}

Recommended Posts

[Swift] How to fix Label in UIPickerView
[swift5] How to specify color in hexadecimal
How to fix system date in JUnit
How to overwrite Firebase data in Swift
[How to use label]
How to add sound in the app (swift)
How to execute tasks in parallel in Swift in Swift Package
[Swift] How to pass the Label value in the selected collectionViewCell to the destination TextField
How to fix a crash when deleting Realm data in Swift UI List
[Swift] How to use UserDefaults
How to use Swift UIScrollView
How to implement infinite scrolling (page nate) in Swift TableView
[Swift5] How to avoid applying dark mode (dark appearance) in code
How to change BackgroundColor etc. of NavigationBar in Swift UI
How to use Lombok in Spring
How to find May'n in XPath
How to hide scrollbars in WebView
How to run JUnit in Eclipse
How to iterate infinitely in Ruby
[Rails] How to write in Japanese
How to run Ant in Gradle
How to master programming in 3 months
How to learn JAVA in 7 days
How to get parameters in Spark
How to install Bootstrap in Ruby
[Swift] How to use SwiftLint (cocoapods)
[Swift] How to use Unwind segue
How to use InjectorHolder in OpenAM
[Swift] How to send a notification
How to introduce jQuery in Rails 6
How to use classes in Java?
How to name variables in Java
How to set Lombok in Eclipse
[Swift] How to replace multiple strings
How to concatenate strings in java
How to install Swiper in Rails
How to fix garbled Japanese characters in JAVA (including Arduino IDE)
Shorten the UUID to base64 in Swift.
How to implement search functionality in Rails
How to implement date calculation in Java
How to implement Kalman filter in Java
Multilingual Locale in Java How to use Locale
How to change app name in rails
How to get date data in Ruby
How to reflect seeds.rb in production environment
How to filter JUnit Test in Gradle
How to insert a video in Rails
How to standardize header footer in Thymeleaf
How to include Spring Tool in Eclipse 4.6.3?
How to add jar file in ScalaIDE
How to do base conversion in Java
[Swift] How to use Tab Bar Controller
How to call Swift 5.3 code from Objective-C
How to have params in link_to method
How to use Docker in VSCode DevContainer
How to use MySQL in Rails tutorial
[Swift] How to implement the countdown function
How to implement coding conventions in Java
How to embed Janus Graph in Java
[rails] How to configure routing in resources
How to map tsrange type in Hibernate