如何在我的 UIViewController 类中声明 UIImageView 以便其他类可以使用它?
Posted
技术标签:
【中文标题】如何在我的 UIViewController 类中声明 UIImageView 以便其他类可以使用它?【英文标题】:how to declare UIImageView in my UIViewController class so that other classes can use it? 【发布时间】:2021-04-23 18:29:02 【问题描述】:I will use GCD to run tasks that will in turn send tasks, that use wrist_band_UIImageView, to GCD main to display.
IE.
1. ViewController starts backend task onto DispatchQueue.global which is an endless loop
2. this endless loop periodically needs to update the UIImageView and so puts a task onto main queue to update the UIImageView.
class ViewController: UIViewController <<<<<< E R R O R Class 'ViewController' has no initializers
@IBOutlet weak var app_title: UILabel!
//////////////////////// VARIABLES ////////////////////////////
var wrist_band_UIImageView: UIImageView
override func viewDidLoad() ///////////////////////////////////////// VIEW DID LOAD
print("viewDidLoad...")
super.viewDidLoad()
// Init data:
let image = UIImage(systemName: "applewatch")
self.wrist_band_UIImageView = UIImageView(image: image!)
print("viewDidLoad starts run_app.")
DispatchQueue.global().async app_class.run_app()
print("viewDidLoad done.")
return
更新: 我将 UIImageView 从静态更改为实例,现在类行生成错误“类 'ViewController' 没有初始化程序”。
【问题讨论】:
你的问题真的没有意义。为什么会有一个UIImageView
的静态变量? UIImageView
属于单个视图层次结构。这是安装在应用主屏幕上的图像视图还是其他什么?
您所说的“......发送使用手腕带_UIImageView的任务到GCD主显示是什么意思?”
已将静态更改为实例,但现在在类行出现错误:类 'ViewController' 没有初始化程序
【参考方案1】:
我发现这个例子可以解决问题............
Class ViewController: UIViewController
let someImageView: UIImageView =
let theImageView = UIImageView()
theImageView.image = UIImage(named: "yourImage.png")
theImageView.translatesAutoresizingMaskIntoConstraints = false //You need to call this property so the image is added to your view
return theImageView
()
override func viewDidLoad()
super.viewDidLoad()
view.addSubview(someImageView) //This add it the view controller without constraints
someImageViewConstraints() //This function is outside the viewDidLoad function that controls the constraints
// do not forget the `.isActive = true` after every constraint
func someImageViewConstraints()
someImageView.widthAnchor.constraint(equalToConstant: 180).isActive = true
someImageView.heightAnchor.constraint(equalToConstant: 180).isActive = true
someImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
someImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 28).isActive = true
【讨论】:
以上是关于如何在我的 UIViewController 类中声明 UIImageView 以便其他类可以使用它?的主要内容,如果未能解决你的问题,请参考以下文章
UIImageView 作为我的 UIViewController 类中 UIView 的子视图
在非 UIViewController 类中呈现 UIAlertController 时如何隐藏状态栏?