我是Jasmeen Bong。我想在屏幕顶部创建一个带有单个按钮(UIButton)的新应用程序。我创建并添加一个名为RandomObject.swift的文件到我的项目中。按下按钮时,我的应用程序将从RandomObject类调用randomObject类方法。
下面是我的RandomObject文件中的代码。在这个文件中,我想编写一个函数,它将随机返回UIView或UILabel。
class RandomObject: NSObject {
//create a frame for the object
class func _randomFrame() -> CGRect {
let x: CGFloat = CGFloat(arc4random() % 220)
let y: CGFloat = CGFloat((arc4random() % 200) + 100)
return CGRect(x: x, y: y, width: 100, height: 100)
}
//create an uilabel
class func _createUILabel() -> UILabel {
let randomFrame: CGRect = RandomObject._randomFrame()
let label = UILabel(frame: randomFrame)
label.text = "UILabel"
return label
}
//create a uiview
class func _createUIView() -> UIView {
let randomFrame: CGRect = RandomObject._randomFrame()
let aView = UIView(frame: randomFrame)
return aView
}
class func randomObject() -> Any {
// create a random generator that get value between 0 - 7
arc4random_stir()
let randomNum: Int = Int(arc4random() % 2)
// Return value of anonymous type, but conforms to NSObject protocol
var returnObj: NSObject? = nil
//use switch case to create returnObj randomly
switch randomNum {
case 0:
returnObj = RandomObject._createUILabel()
case 1:
returnObj = RandomObject._createUIView()
default:
print("error")
}
//return the returnObj
return returnObj
}
}
这是我在viewController文件中编写的编码。在这里,我想调用randomObject函数并检查返回的对象是否是UIView。如果是UIView,则将其背景颜色设置为随机颜色,并将其添加为子视图。
class ViewController: UIViewController {
@IBAction func PressMeButton(_ sender: Any)
{
let aObj = RandomObject.randomObject()
//check if aObj is a UIView
if (aObj is UIView) {
let myView = aObj as? UIView
let red = CGFloat(arc4random()) / CGFloat(RAND_MAX)
let blue = CGFloat(arc4random()) / CGFloat(RAND_MAX)
let green = CGFloat(arc4random()) / CGFloat(RAND_MAX)
let randomColor: UIColor? = UIColor(red: red, green: blue, blue: green, alpha: 1)
myView?.backgroundColor = randomColor
self.view.addSubview(myView!)
}
}
但我的问题是我的if声明:
if (aObj is UIView)
它无法帮助我检查返回的对象是UIView和UILabel。因此,UILabel也将作为子视图添加。我可以知道如何解决这个问题吗? 非常感谢你的帮助。
答案 0 :(得分:0)
由于UILabel继承自UIView,因此您的支票aObj is UIView
将成功。如果您想以不同方式处理UILabel,则需要先检查它们:
if let lbl = aObj as? UILabel {
// do label stuff
} else if let view = aObj as? UIView {
// do view stuff
}