programing

완료 버튼으로 UI Picker View를 만드는 방법은 무엇입니까?

abcjava 2023. 8. 4. 22:33
반응형

완료 버튼으로 UI Picker View를 만드는 방법은 무엇입니까?

사용자가 UI 텍스트 필드를 탭할 때 나타나는 완료 버튼으로 UI PickerView를 만드는 데 어려움이 있습니다.지금까지 제 코드입니다.모든 것이 정상적으로 빌드되지만 텍스트 필드를 누르면 선택기가 아닌 키보드가 나타납니다.

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {


@IBOutlet var textField1: UITextField!

let pickerData = ["11", "12", "13"]





@IBAction func textButton(sender: AnyObject) {

    let picker: UIPickerView
    picker = UIPickerView(frame: CGRectMake(0, 200, view.frame.width, 300))
    picker.backgroundColor = .whiteColor()

    picker.showsSelectionIndicator = true
    picker.delegate = self
    picker.dataSource = self

    let toolBar = UIToolbar()
    toolBar.barStyle = UIBarStyle.Default
    toolBar.translucent = true
    toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
    toolBar.sizeToFit()

    let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker")
    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker")

    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    toolBar.userInteractionEnabled = true

    textField1.inputView = picker
    textField1.inputAccessoryView = toolBar




}



override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return pickerData.count
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return pickerData[row]
}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    textField1.text = pickerData[row]
}

func donePicker() {

    textField1.resignFirstResponder()

}




}

이 코드를 에 추가합니다.viewDidLoad()방법 대신에

let picker: UIPickerView
picker = UIPickerView(frame: CGRectMake(0, 200, view.frame.width, 300))
picker.backgroundColor = .whiteColor()

picker.showsSelectionIndicator = true
picker.delegate = self
picker.dataSource = self

let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
toolBar.sizeToFit()

let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.done, target: self, action: #selector(self. donePicker))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItem.Style.plain, target: self, action: #selector(self. donePicker))

toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true

textField1.inputView = picker
textField1.inputAccessoryView = toolBar

컨트롤러에서 코드를 제거하는 커스텀 클래스를 만드는 것이 좋을 것 같습니다.

Swift 4/5 예:

import Foundation
import UIKit

protocol ToolbarPickerViewDelegate: class {
    func didTapDone()
    func didTapCancel()
}

class ToolbarPickerView: UIPickerView {

    public private(set) var toolbar: UIToolbar?
    public weak var toolbarDelegate: ToolbarPickerViewDelegate?

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.commonInit()
    }

    private func commonInit() {
        let toolBar = UIToolbar()
        toolBar.barStyle = UIBarStyle.default
        toolBar.isTranslucent = true
        toolBar.tintColor = .black
        toolBar.sizeToFit()

        let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.doneTapped))
        let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(self.cancelTapped))

        toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
        toolBar.isUserInteractionEnabled = true

        self.toolbar = toolBar
    }

    @objc func doneTapped() {
        self.toolbarDelegate?.didTapDone()
    }

    @objc func cancelTapped() {
        self.toolbarDelegate?.didTapCancel()
    }
}

사용 예:

class MyViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!
    fileprivate let pickerView = ToolbarPickerView()
    fileprivate let titles = ["0", "1", "2", "3"]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.textField.inputView = self.pickerView
        self.textField.inputAccessoryView = self.pickerView.toolbar

        self.pickerView.dataSource = self
        self.pickerView.delegate = self
        self.pickerView.toolbarDelegate = self

        self.pickerView.reloadAllComponents()
    }
}

extension MyViewController: UIPickerViewDataSource, UIPickerViewDelegate {

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return self.titles.count
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return self.titles[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        self.textField.text = self.titles[row]
    }
}

extension MyViewController: ToolbarPickerViewDelegate {

    func didTapDone() {
        let row = self.pickerView.selectedRow(inComponent: 0)
        self.pickerView.selectRow(row, inComponent: 0, animated: false)
        self.textView.text = self.titles[row]
        self.textField.resignFirstResponder()
    }

    func didTapCancel() {
        self.textField.text = nil
        self.textField.resignFirstResponder()
    }
}

완료 단추가 있는 UI 선택기 보기?스위프트4

1단계: ViewController에서 txt_pickUpData라는 textFiled를 추가하고 IOutlet 연결 및 위임을 제공합니다.또한 UIDatePicker 변수 하나를 사용합니다.선택기 휠에 표시되는 문자열 값이 있는 배열을 선택합니다.

@IBOutlet weak var txt_pickUpData: UITextField!
var myPickerView : UIPickerView!
var pickerData = ["Hitesh Modi" , "Kirit Modi" , "Ganesh Modi" , "Paresh Modi"]

2단계 : UIPickerView 및 UITextFiled의 대리자도 추가합니다.

class ViewController: UIViewController , UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate{

3단계 : ToolBar를 사용하여 UIPickerView를 생성하는 기능 pickUp.

func pickUp(_ textField : UITextField){

// UIPickerView
self.myPickerView = UIPickerView(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216))
self.myPickerView.delegate = self
self.myPickerView.dataSource = self
self.myPickerView.backgroundColor = UIColor.white
textField.inputView = self.myPickerView

// ToolBar
let toolBar = UIToolbar()
toolBar.barStyle = .default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
toolBar.sizeToFit()

// Adding Button ToolBar
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ViewController.doneClick))
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(ViewController.cancelClick))
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
textField.inputAccessoryView = toolBar

 }

4단계 : UIPickerView 휠에 데이터를 표시하기 위해 UIPickerView의 대리자 및 데이터 소스 메서드 추가.

//MARK:- PickerView Delegate & DataSource
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
 }
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerData.count
 }
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerData[row]
  }
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.txt_pickUpData.text = pickerData[row]
 }
 //MARK:- TextFiled Delegate

 func textFieldDidBeginEditing(_ textField: UITextField) {
self.pickUp(txt_pickUpData)
 }

5단계 : ToolBar에 있는 두 개의 버튼 방법 추가.하나는 cancelClick이고 다른 하나는 cancelClick입니다.즉, UIPickerView를 해제합니다.

@objc func doneClick() {
  txt_pickUpData.resignFirstResponder()
 }
@objc func cancelClick() {
  txt_pickUpData.resignFirstResponder()
}

6단계: UITextField 대리자 메서드에서 pickUp 함수 호출.

func textFieldDidBeginEditing(_ textField: UITextField) {
self.pickUp(txt_pickUpData)
}

코드를 복사하여 붙여넣기만 하면 됩니다.

사람들은 VBaraathi가 질문한 것과 같은 것을 묻기 위해 여기 있는 코드를 다른 질문에 사용하는 것 같습니다.

인 스위프트3

let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(donePicker))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: #selector(donePicker))

그러면 다음 사항을 동일한 신속한 파일에 넣을 수 있습니다.

func donePicker (sender:UIBarButtonItem)
{
     // Put something here
}

Swift 3x:

멋진 대답은 이미 제공되었지만 여기 다른 접근법이 있습니다. 그냥 해보세요.pickerView그리고 그것을 주어라.inputView그리고.inputAccessoryView다음과 같이:

YOUR_TEXTFIELD_NAME.inputView = picker


func addKeyboardToolBar() {

  var nextButton: UIBarButtonItem?
  var keyboardToolBar = UIToolbar(frame: CGRect(x: CGFloat(0), y: 
  CGFloat(0), width: CGFloat(pickerView.frame.size.width), height: CGFloat(25)))
  keyboardToolBar.sizeToFit()
  keyboardToolBar.barStyle = .default
  daysHourTextField.inputAccessoryView = keyboardToolBar
  nextButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.textFieldShouldReturn))
  keyboardToolBar.items = [UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), nextButton]

}

IQKeyboard Manager 라이브러리를 사용합니다.설정 후에는 자동으로 완료 버튼이 추가됩니다.여기에서 확인해 보세요: github.

먼저 포드를 설치합니다.

pod 'IQKeyboardManagerSwift'

그런 다음 AppDelegate.swift에서 IQKeyboardManagerSwift 프레임워크를 가져오고 IQKeyboardManager를 활성화합니다.

 import IQKeyboardManagerSwift

 @UIApplicationMain
 class AppDelegate: UIResponder, UIApplicationDelegate {

   var window: UIWindow?

   func application(_ application: UIApplication, 
    didFinishLaunchingWithOptions launchOptions: 
    [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    IQKeyboardManager.shared.enable = true

    return true
  }
}

이 라이브러리는 자동으로 키보드에 완료 단추를 추가합니다.

언급URL : https://stackoverflow.com/questions/31728680/how-to-make-an-uipickerview-with-a-done-button

반응형