我正在尝试使用计时器每3秒更新一次背景颜色并计算随机颜色值并将它们分配给背景。我已经完成了这个,但问题是当我在主线程上运行我的代码时,UITextField
将不再响应!
//
// ViewBG.swift
// E-Sign
//
// Created by shayan rahimian on 1/30/18.
// Copyright © 2018 shayan rahimian. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController{
@objc func changeBG(){
//background style!
DispatchQueue.global(qos: .utility).async {
let red = Float((arc4random() % 256)) / 255.0
let green = Float((arc4random() % 256)) / 255.0
let blue = Float((arc4random() % 256)) / 255.0
let alpha = Float(1.0)
DispatchQueue.main.async {
UIView.animate(withDuration: 3.0, delay: 0.0, options:[.repeat, .autoreverse], animations: {
self.view.backgroundColor = UIColor(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(alpha))}, completion:nil)
}
}
//end of background style
}
@objc func Blur(){
//Blur BackGround
let blur = UIBlurEffect(style: .light)
let blurview = UIVisualEffectView(effect: blur)
blurview.frame = self.view.frame
blurview.alpha = 0.7
self.view.insertSubview(blurview, at: 0)
//End of Blur
}
@objc func DoBG(){
DispatchQueue.main.async {
self.Blur()
_ = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(UIViewController.changeBG), userInfo: nil, repeats: true)
}
}
}
背景工作正常,但我的文本字段不会编辑!有没有办法在后台线程或任何工作中改变背景颜色?
任何帮助将不胜感激
答案 0 :(得分:2)
一些建议:
1)删除DispatchQueue.global(qos: .utility).async
(对于此类操作,您并不真正需要它),只保留main.async
2)禁用blurview.isUserInteractionEnabled = false
上的互动,我不知道您的等级制度如何,但如果触及某些其他子视图,可能会有害。
3)你的计时器每隔3秒调用changeBG
,这样的函数用repeat, .autoreverse
开始动画:我猜这是一个不好的机制(你可能会冻结ViewController
或者崩溃应用程序)因为你一直在添加循环forever的动画。
4)在[.repeat, .autoreverse, .allowUserInteraction]