我正在尝试使用计时器每 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)
}
}
}
背景工作正常,但我的文本字段无法编辑! 有没有办法更改背景线程中的背景颜色或任何解决方法?
任何帮助将不胜感激
一些建议:
1(删除DispatchQueue.global(qos: .utility).async
(对于此类操作,您并不真正需要它(,仅保留main.async
2(禁用blurview.isUserInteractionEnabled = false
上的交互,我不知道您的层次结构如何,但如果它代替其他一些子视图进行触摸可能会有害。
(你的计时器每3秒调用changeBG
一次,这样的函数用repeat, .autoreverse
启动动画:我想这是一个糟糕的机制(你可能会冻结ViewController
或使应用程序崩溃(,因为你一直在添加永远循环的动画。
4(在[.repeat, .autoreverse, .allowUserInteraction]
中更改动画的选项