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()
IntelliSense를 나타납니다,하지만 일을하지 않습니다.
당신의 도움을 주셔서 감사합니다.
편집 : 후세를 위해 다음 작품 :
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) {
}
메서드 이름이 어떻게 생겼는지 확실하지 않은 경우 매우 유용한 특수 버전의 복사 명령이 있습니다. 기본 메서드 이름 (예 : sayHello)에 커서를 놓고 Shift+ Control+ Option+를 누릅니다 C. 붙여 넣을 키보드에 '기호 이름'이 입력됩니다. 또한 보유 Command하면 유형도 포함하는 '정규화 된 기호 이름'이 복사됩니다.
스위프트 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/#compile-time-checked-selectors를 참조하세요.
Swift 4 예제
button.action = #selector(buttonClicked(sender:))
@objc func buttonClicked(sender: UIBarButtonItem) {
}
참고 URL : https://stackoverflow.com/questions/24641350/how-to-set-the-action-for-a-uibarbuttonitem-in-swift
'Program Tip' 카테고리의 다른 글
파일이없는 폴더 및 하위 폴더 목록을 얻으려면 어떻게합니까? (0) | 2020.10.18 |
---|---|
Git 실행 취소 병합 시도 (0) | 2020.10.18 |
의존성 주입 및 싱글 톤 디자인 패턴 (0) | 2020.10.18 |
선언 된 패키지가 예상 패키지 ""와 일치하지 않습니다. (0) | 2020.10.18 |
ArrayList로 Parcelable을 올바르게 구현하는 방법 (0) | 2020.10.18 |