更新到Swift 2.2和Xcode 7.3后,我重复的NSTimer已停止重复。
let timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: #selector(rotate), userInfo: nil, repeats: true)
timer.fire()
选择器触发一次,然后再次开火,直到窗口关闭或最小化。
其他人?有什么建议吗?
答案 0 :(得分:4)
定时器需要在同一个线程中始终被调度或无效,您可能在异步块内调用它吗?尝试在主队列中安排它:
public Image resizeImage(int newWidth, int newHeight, string stPhotoPath)
{
Image imgPhoto = Image.FromFile(stPhotoPath);
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
//Consider vertical pics
if (sourceWidth < sourceHeight)
{
int buff = newWidth;
newWidth = newHeight;
newHeight = buff;
}
int sourceX = 0, sourceY = 0, destX = 0, destY = 0;
float nPercent = 0, nPercentW = 0, nPercentH = 0;
nPercentW = ((float)newWidth / (float)sourceWidth);
nPercentH = ((float)newHeight / (float)sourceHeight);
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = System.Convert.ToInt16((newWidth -
(sourceWidth * nPercent)) / 2);
}
else
{
nPercent = nPercentW;
destY = System.Convert.ToInt16((newHeight -
(sourceHeight * nPercent)) / 2);
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap bmPhoto = new Bitmap(newWidth, newHeight,
PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.Clear(Color.Black);
grPhoto.InterpolationMode =
System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
imgPhoto.Dispose();
return bmPhoto;
}
答案 1 :(得分:1)
func startTimer() {
let timer = NSTimer(timeInterval: 1, target: self, selector: #selector(MainViewController.updateLabel), userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
}
这适用于Swift 2.2 苹果文档没有提及dispatch_async的任何内容。有没有理由使用它......只是好奇......还在学习
使用timerWithTimeInterval:invocation:repeats:或timerWithTimeInterval:target:selector:userInfo:repeats:class方法创建计时器对象而不在运行循环上调度它。 (创建它之后,必须通过调用相应NSRunLoop对象的addTimer:forMode:方法手动将计时器添加到运行循环中。)
答案 2 :(得分:0)
dispatch_async(dispatch_get_main_queue()) {
self.timer = NSTimer(timeInterval:1.0, target:self, selector: #selector(self.rotate), userInfo:nil, repeats:true)
NSRunLoop.currentRunLoop().addTimer(self.timer!, forMode: NSRunLoopCommonModes)
}
这是一个线程问题,也没有在NSRunLoop中自动添加或处理。在同一个线程上手动执行此操作修复它。
感谢大家的帮助和建议。