我正在创建UIStackView
,并在一个循环中创建一定数量的UILabel
和UISwitch
对,并将它们添加到UIStackView
中。现在如何获得UISwitch
的状态为 ON 或 OFF ?
func addAnswrsToTheStack(using answers: [Answer]){
createHorizontalStackView()
horizontalStackView.addArrangedSubview(questionProgressView)
var questionSwitch: UISwitch!
for answer in answers {
createHorizontalStackView()
let label: UILabel = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.textAlignment = .left
label.text = answer.text
horizontalStackView.addArrangedSubview(label)
questionSwitch = UISwitch()
questionSwitch.isOn = false
horizontalStackView.addArrangedSubview(questionSwitch)
}
}
答案 0 :(得分:0)
您可以通过调用UISwitch
来获得isOn
的值,方法与设置相同。您可以遍历stackView中的所有视图,使用
for view in horizontalStackView.arrangedSubviews {
if view is UISwitch {
// check the value here
}
}
答案 1 :(得分:0)
您可以尝试
for (index,answer) in answers.enumerated() {
....
questionSwitch = UISwitch()
questionSwitch.tag = index
questionSwitch.isOn = false
questionSwitch.addTarget(self, action: #selector(switchChanged), for:.valueChanged)
}
@objc func switchChanged(_ mySwitch: UISwitch) {
let value = mySwitch.isOn
print(mySwitch.tag , value)
}
答案 2 :(得分:0)
您不知道每个答案的开关状态,因为您仅创建了开关,但没有保存该关联。一种干净的方法是具有Answer和UISwitch的wrappertype。但是,让我们暂时不要这样做。
您需要返回一个映射,告诉您哪个开关与哪个问题相关。
类型[Answer:UISwitch]将起作用,仅此而已。现在,您可以查找每个Switch及其状态以获得答案。
class OrderListView(SingleTableMixin,FilterView):
table_class = OrderTable
model = Order
template_name='orders/orde_list.html'
filterset_class = OrderFilter
def get_context_data(self, **kwargs):
context = super(OrderListView, self).get_context_data(**kwargs)
##filter the orders of the past 4 months.
last_four_months=date.today() - timedelta(120)
object_list=Order.objects.filter(order_created__gte=last_four_months,ays=1).order_by('-invoice_date')
table=self.table_class(object_list)
RequestConfig(self.request).configure(table)
context['table'] = table
#clear all fields
has_filter = any(field in self.request.GET for field in set(self.filterset_class.get_fields()))
context['has_filter'] = has_filter
return context