Swift 3:通过遍历视图数组来设置视图
Posted
技术标签:
【中文标题】Swift 3:通过遍历视图数组来设置视图【英文标题】:Swift 3 : Setting a view by iterating through an array of views 【发布时间】:2017-05-08 09:47:02 【问题描述】:我有四个 UIView 对象,它们最初是可选的。然后,当我加载视图时,它们被放入一个数组并在一个 for 循环中,它们中的每一个都被分配了一个 UIStackView。但是当我检查对象的全局实例是否等于数组中的一个时,它不是。我现在真的很困惑。
//global
@IBOutlet weak var buttonA: UIButton!
@IBOutlet weak var buttonB: UIButton!
@IBOutlet weak var buttonC: UIButton!
@IBOutlet weak var buttonD: UIButton!
var answerAView: UIView?
var answerBView: UIView?
var answerCView: UIView?
var answerDView: UIView?
override func viewDidLoad()
var answersViews = [self.answerAView, self.answerBView, self.answerCView, self.answerDView]
var buttons = [buttonA, buttonB, buttonC, buttonD]
var answers = ["A", "B", "C", "D"]
var count = 0
for a in answers
let newStack = UIStackView()
newStack.axis = .vertical
let label = UILabel()
label.textColor = UIColor.black
label.text = a
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
newStack.addArrangedSubview(label)
newStack.distribution = .fillEqually
newStack.spacing = 10
NSLayoutConstraint(item: buttons[count], attribute: .width, relatedBy: .equal, toItem: rows[count], attribute:.width, multiplier: 0.15, constant:0.0).isActive = true
answersViews[count] = newStack
if answerAView == answersViews[count]
print("Settkekasldfjkskdjblvkjbalkvbksjbvb")//this does not print
count += 1
【问题讨论】:
似乎您的代码在语法方面几乎没有错误...请发布完整的源代码..它会有所帮助 【参考方案1】:也许你应该写如下
//global
var answerAView: UIView?
var answerBView: UIView?
var answerCView: UIView?
var answerDView: UIView?
//inside viewDidLoad
var answersViews = [answerAView, answerBView, answerCView, answerDView]
for view in answersViews
let stackView = UIStackView()
stackView.addSubview(view)
print("success")
【讨论】:
我更新了代码,你可以看到我需要uiview变成stack view 你写的代码“answersViews[count] = newStack”是错误的 为什么当我使用@IBOutlet weak var answerA: UITextView 时它会起作用?如 answerAview = answerA.以上是关于Swift 3:通过遍历视图数组来设置视图的主要内容,如果未能解决你的问题,请参考以下文章
Swift 3 - 带有 Tap Gesture 的图像视图