我们考虑以下代码:
protocol A {
func doA()
}
extension A {
func registerForNotification() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardDidShow:"), name: UIKeyboardDidShowNotification, object: nil)
}
func keyboardDidShow(notification: NSNotification) {
}
}
Run Code Online (Sandbox Code Playgroud)
现在看一下实现A的UIViewController子类:
class AController: UIViewController, A {
override func viewDidLoad() {
super.viewDidLoad()
self.registerForNotification()
triggerKeyboard()
}
func triggerKeyboard() {
// Some code that make key board appear
}
func doA() {
}
}
Run Code Online (Sandbox Code Playgroud)
但令人惊讶的是,这会因错误而崩溃:
keyboardDidShow:]:无法识别的选择器发送到实例0x7fc97adc3c60
那么我应该在视图控制器本身中实现观察者吗?不能留在延期?
以下事情已经尝试过.
制作A类协议.将keyboardDidShow添加到协议本身作为签名.
protocol A:class {
func doA()
func keyboardDidShow(notification: NSNotification)
}
Run Code Online (Sandbox Code Playgroud) 我试图在Objective-C代码中使用Swift类,但是我的Swift类似乎没有出现在生成的头文件中.结果,我的构建失败了"使用未声明的标识符'HelloWorld'".
我使用模板创建了一个名为TestApp的项目.
我的目标中有以下构建设置:
Apple的文档说要使用,#import <TestApp/TestAppModule-Swift.h>但这不起作用.
相反,我#import "TestAppModule-Swift.h"在我的".m"文件中使用.它似乎找到了这个.
我能够导航到它,它看起来像这样......
// Generated by Swift version 1.0 (swift-600.0.34.4.5)
#if defined(__has_include) && __has_include(<swift/objc-prologue.h>)
# include <swift/objc-prologue.h>
#endif
...etc...
Run Code Online (Sandbox Code Playgroud)
但没有在那里定义的类.
我在项目中有一个Swift文件,看起来像这样......
class HelloWorld {
func hello() {
println("hello world")
}
}
Run Code Online (Sandbox Code Playgroud)
为什么这不使用标准头文件位置#import <TestApp/TestAppModule-Swift.h>?
如何在头文件中获取我的swift类,这样我就不会得到"未声明的标识符"错误?
我想知道是否可以获取a的名称UILabel(而不是文本)。
像这样:
if([label.name is equalToString:key]){
//do something
}
Run Code Online (Sandbox Code Playgroud)
我知道label.name不存在,但也许有等同的东西。我怎样才能做到这一点?