programing

Swift에서 UIBarButtonItem에 대한 작업을 설정하는 방법

elecom 2023. 8. 16. 21:57
반응형

Swift에서 UIBarButtonItem에 대한 작업을 설정하는 방법

Swift에서 사용자 지정 UIBarButtonItem에 대한 작업은 어떻게 설정할 수 있습니까?

다음 코드는 버튼을 탐색 모음에 성공적으로 배치합니다.

var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:nil)
self.navigationItem.rightBarButtonItem = b

이제 전화를 드리고 싶습니다.func sayHello() { println("Hello") }버튼을 누르면 됩니다.지금까지의 노력:

var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:sayHello:)
// also with `sayHello` `sayHello()`, and `sayHello():`

그리고..

var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:@selector(sayHello:))
// also with `sayHello` `sayHello()`, and `sayHello():`

그리고..

var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:@selector(self.sayHello:))
// also with `self.sayHello` `self.sayHello()`, and `self.sayHello():`

참고:sayHello()인텔리전트에 나타나지만 작동하지 않습니다.

도와주셔서 고마워요.

편집: 후세를 위해 다음과 같은 작업을 수행합니다.

var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:"sayHello")

Swift 2.2부터는 컴파일러 시간 검사 선택기를 위한 특별한 구문이 있습니다.구문은 다음과 같습니다.#selector(methodName).

Swift 3 이상:

var b = UIBarButtonItem(
    title: "Continue",
    style: .plain,
    target: self,
    action: #selector(sayHello(sender:))
)

func sayHello(sender: UIBarButtonItem) {
}

메서드 이름이 어떻게 표시되어야 하는지 잘 모를 경우, copy 명령어의 특수 버전이 매우 유용합니다.기본 메서드 이름(예: 안녕하세요)의 어딘가에 커서를 놓고 +++ControlOptionC를 누릅니다.그러면 키보드에 붙여넣을 '기호 이름'이 표시됩니다.또한 누른 상태에서 '정규화된 기호 이름'을 복사하면 형식도 포함됩니다.

Swift 2.3:

var b = UIBarButtonItem(
    title: "Continue",
    style: .Plain,
    target: self,
    action: #selector(sayHello(_:))
)

func sayHello(sender: UIBarButtonItem) {
}

이는 메서드 호출 시 Swift 2.3에서 첫 번째 매개 변수 이름이 필요하지 않기 때문입니다.

구문에 대한 자세한 내용은 swift.org 에서 확인할 수 있습니다. https://swift.org/blog/swift-2-2-new-features/ #http-time-checked-selectors

Swift 4/5 예제

button.target = self
button.action = #selector(buttonClicked(sender:))

@objc func buttonClicked(sender: UIBarButtonItem) {
        
}

Swift 5 & iOS 13+ 프로그램 예시

  1. 다음을 사용하여 기능을 표시해야 합니다.@objc아래 예를 참조하십시오!
  2. 함수 이름 뒤에 괄호가 없습니다!그냥 사용하기#selector(name).
  3. private또는public상관없습니다. 개인 정보를 사용할 수 있습니다.

코드 예제

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    let menuButtonImage = UIImage(systemName: "flame")
    let menuButton = UIBarButtonItem(image: menuButtonImage, style: .plain, target: self, action: #selector(didTapMenuButton))
    navigationItem.rightBarButtonItem = menuButton
}

@objc public func didTapMenuButton() {
    print("Hello World")
}

이것이 조금 더 도움이 되길 바랍니다.

모듈식 접근 방식을 위해 별도의 파일로 막대 단추를 만들고 선택기를 뷰 컨트롤러에 반환하려면 다음과 같이 할 수 있습니다.

유틸리티 파일

class GeneralUtility {

    class func customeNavigationBar(viewController: UIViewController,title:String){
        let add = UIBarButtonItem(title: "Play", style: .plain, target: viewController, action: #selector(SuperViewController.buttonClicked(sender:)));  
      viewController.navigationController?.navigationBar.topItem?.rightBarButtonItems = [add];
    }
}

그런 다음 SuperviewController 클래스를 만들고 이 클래스에 동일한 함수를 정의합니다.

class SuperViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
            // Do any additional setup after loading the view.
    }
    @objc func buttonClicked(sender: UIBarButtonItem) {

    }
}

그리고 기본 뷰에서 컨트롤러(SuperviewController 클래스를 상속함)는 동일한 기능을 재정의합니다.

import UIKit

class HomeViewController: SuperViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func viewWillAppear(_ animated: Bool) {
        GeneralUtility.customeNavigationBar(viewController: self,title:"Event");
    }

    @objc override func buttonClicked(sender: UIBarButtonItem) {
      print("button clicked")    
    } 
}

이제 이 막대 단추를 원하는 클래스의 SuperViewController를 상속합니다.

읽어주셔서 감사합니다.

스위프트 5

생성한 경우UIBarButtonItem아웃렛을 항목에 연결하고 선택기를 프로그래밍 방식으로 바인딩하려고 합니다.

목표와 선택기를 설정하는 것을 잊지 마세요.

addAppointmentButton.action = #selector(moveToAddAppointment)
addAppointmentButton.target = self

@objc private func moveToAddAppointment() {
     self.presenter.goToCreateNewAppointment()
}

사용하지 않으려는 경우target/action용사를 #selector사용할 수 있습니다.primaryAction 이래iOS 14:

// here you can set the title or a image for the UIBarButtonItem
let action = UIAction(title: "", image: UIImage(systemName: "list.dash")) { _ in
    // handler
    print("hello world")
}
        
let barButtonItem = UIBarButtonItem(title: nil,
                                    image: nil,
                                    primaryAction: action,
                                    menu: nil)

언급URL : https://stackoverflow.com/questions/24641350/how-to-set-the-action-for-a-uibarbuttonitem-in-swift

반응형