我一直在经历所有堆栈溢出,试图解决这个问题,但没有一个解决方案可以解决。
class ToastView: UIView {
static func showInParent(parentView: UIView!, withText text: String, forDuration duration: double_t) {
//Count toast views are already showing on parent. Made to show several toasts one above another
var toastsAlreadyInParent = 0;
for view in parentView.subviews {
if (view.isKindOfClass(ToastView)) {
toastsAlreadyInParent++
}
}
var parentFrame = parentView.frame;
var yOrigin = parentFrame.size.height - getDouble(toastsAlreadyInParent)
var selfFrame = CGRectMake(parentFrame.origin.x + 20.0, yOrigin, parentFrame.size.width - 40.0, toastHeight);
var toast = ToastView(frame: selfFrame)
toast.textLabel.backgroundColor = UIColor.clearColor()
toast.textLabel.textAlignment = NSTextAlignment.Center
toast.textLabel.textColor = UIColor.whiteColor()
toast.textLabel.numberOfLines = 2
toast.textLabel.font = UIFont.systemFontOfSize(13.0)
toast.addSubview(toast.textLabel)
toast.backgroundColor = UIColor.darkGrayColor()
toast.alpha = 0.0;
toast.layer.cornerRadius = 4.0;
toast.textLabel.text = text;
parentView.addSubview(toast)
UIView.animateWithDuration(0.4, animations: {
toast.alpha = 0.9
toast.textLabel.alpha = 0.9
})
var timer = NSTimer.scheduledTimerWithTimeInterval(duration, target: self , selector: "hideSelf:", userInfo: nil, repeats: false)
//toast.performSelector(Selector("hideSelf"), withObject: nil, afterDelay: duration)
}
static private func getDouble(toastsAlreadyInParent : Int) -> CGFloat {
return (70.0 + toastHeight * CGFloat(toastsAlreadyInParent) + toastGap * CGFloat(toastsAlreadyInParent));
}
func hideSelf( timer: NSTimer) {
UIView.animateWithDuration(0.4, animations: {
self.alpha = 0.0
self.textLabel.alpha = 0.0
}, completion: { t in self.removeFromSuperview() })
}
}
这是我得到的错误:
NSInvalidArgumentException',原因:' + [HonorsApp.ToastView hideSelf:]:无法识别的选择器发送到类0x10b564530' ***首先抛出调用堆栈:
我尝试将@objc添加到从选择器和类调用的方法中但是它没用了
此外:
Selector("hideSelf")
将方法声明为hideSelf()
Selector("hideSelf:")
将方法声明为hideSelf( timer: NSTimer)
还检查了该类继承自NSObject,这是通过继承UIView完成的,如果我没有错的话。
我正在使用XCode 6.4
和swift 1.2
我是swift编程的新手,需要像Android中的Toast功能一样的东西,我找到了这个代码,但是一旦我点击运行就出现了错误。
感谢您的帮助。
答案 0 :(得分:11)
由于showInParent
是static
函数,因此self
中使用的NSTimer.scheduledTimerWithTimeInterval
是指类,而不是类的实例。如果没有查找正确的目标,iOS就不会找到实例方法hideSelf
。
尝试将您创建的ToastView
实例传递给计时器:
var timer = NSTimer.scheduledTimerWithTimeInterval(duration, target: toast, selector: "hideSelf:", userInfo: nil, repeats: false)
答案 1 :(得分:0)
试试这段代码。
toast.performSelector(Selector("hideSelf:"), withObject: nil)
或
toast.performSelector(#selector(ClassName.hideSelf(_:)), withObject: nil) s
答案 2 :(得分:0)
更改此行:
var timer = NSTimer.scheduledTimerWithTimeInterval(duration, target: self , selector: "hideSelf:", userInfo: nil, repeats: false)
成:
var timer = NSTimer.scheduledTimerWithTimeInterval(duration, target: toast , selector: "hideSelf:", userInfo: nil, repeats: false)
这应该有所帮助。