设置时UIImageViewImage不会改变

时间:2016-06-02 18:57:48

标签: ios swift uiimage

我已经阅读了StackOverflow上的大约15篇帖子,讨论了UIImageViews的主题并让它们动画交叉渐变。我想最终有一个交叉淡入淡出,但我现在甚至无法改变图像。

我的代码是

var next = 0
let names = ["image_1", "image_2", "image_3", "image_4"]

// While the image is still in memory, keep cycling every few seconds
while ImageView != nil {
    print(next % 4)

    // Grab the new image
    let nextImage = UIImage(named: names[next % 4])
    next++

    // Set the new image
    ImageView.image = nextImage

    // Wait a few seconds
    NSThread.sleepForTimeInterval(NSTimeInterval(4))
}

图片名称来自我的xcassets。当我运行它时,图像不会改变,但循环仍然每隔几秒打印

我做错了什么?

2 个答案:

答案 0 :(得分:1)

没有。错误。忘记你曾经听说过睡眠和它的变种。从主线程来看,这是一个巨大的禁忌。它阻止了用户界面,会导致系统杀死你的应用程序,而且在这种情况下也只是简单的工作。 (在您的代码返回并访问事件循环之前,UI更改才会生效)

您要做的是安装和映像,然后启动计时器或使用dispatch_after排队将在一段时间间隔后显示新图像的代码,然后返回。

您的代码可能如下所示:

mydoclist = []
#below im only taking my field 'Text' as input 
f = open('C:\sample4.csv', "r")
reader = csv.reader(f) 
for row in reader:   
    models.append(row)
f.close()

tf = TfidfVectorizer(tokenizer=lambda doc: doc,lowercase=False, analyzer='word',  min_df = 0, stop_words = 'english')
tfidf_matrix =  tf.fit_transform(mydoclist)
feature_names = tf.get_feature_names()
tfs = tf.fit_transform(mydoclist)
#storing my tfidf matrix
import pickle
with open("x_result.pkl", 'wb') as handle:
    pickle.dump(tfidf_matrix, handle)

答案 1 :(得分:1)

您正在主线程中运行此循环

因此循环会阻止您的MainThread,并且无法更新ImageView。

当您的代码被点击时,UI-Stuff不会立即更新。

您可以这样做:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { 
    while ImageView != nil {
        print(next % 4)

        let nextImage = UIImage(named: names[next % 4])
        next++

        dispatch_async(dispatch_get_main_queue()) { 
            // UI Changes need to be done in the main thread
            ImageView.image = nextImage
        }


        // blocking code needs to be done in another thread
        NSThread.sleepForTimeInterval(NSTimeInterval(4))
    }
}