我想通过for循环将数据绑定到UIImageView-es数组。但我不知道如何绑定像Javascript数据属性一样简单。 我有一个想法,制作一个数组[UIImage:data]来做到这一点。 好的,我的代码出了问题:
问题:
如何在循环中创建与数据绑定的出口?例如,如何将每个变量pattern
绑定到每个操作selectDecoration()
?
func selectDecoration(recognizer: UITapGestureRecognizer) {
print("OK")
}
let patternSelectorHeight: CGFloat = 120
var i : Int = 0
//var patternViews = [UIImageView]()
for pattern in decorationPatterns {
let patternSelector = UIImageView(image: UIImage(named: "test.jpg"))
if let p = patternSelector.image {
let proportion = p.size.width / p.size.height
let w = proportion * patternSelectorHeight
let patternX: CGFloat = (w + Conf.Size.margin) * CGFloat(i) + Conf.Size.margin
let patternOrigin = CGPoint(x: patternX, y: decorationSelectionTitleHeight)
patternSelector.userInteractionEnabled = true
patternSelector.frame = CGRect(origin: patternOrigin, size: CGSize(width: w, height: patternSelectorHeight))
patternSelector.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "selectDecoration:"))
decorationBg.addSubview(patternSelector)
decorationBg.bringSubviewToFront(patternSelector)
//patternViews.append(patternSelector)
}
i++
}
答案 0 :(得分:0)
Swift中没有内置的数据绑定支持。您可能需要在数组中保留对UIImageView
个对象的引用,以便您以后可以更新它们。
您需要设置patterSelector.userInteractionEnabled=true
才能使UITapGestureRecognizer
生效。
let patterSelectorSize = CGSize(width: 80.0, height: 160.0)
var imageViews = [UIImageView]() // This probably needs to be an instance variable so you can access it outside of this function
var i : Int = 0
for _ in decorationPatterns {
let patternX: CGFloat = (patterSelectorSize.width + 10) * CGFloat(i) + 10
let patternOrigin = CGPoint(x: patternX, y: CGFloat(60))
let patterSelector = UIImageView(image: UIImage(named: "default.jpeg"))
patterSelector.frame = CGRect(origin: patternOrigin, size: patterSelectorSize)
patterSelector.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "selectDecoration:"))
patterSelector.userInteractionEnabled=true
imageViews.append(patterSelector)
decorationBg.addSubview(patterSelector)
decorationBg.bringSubviewToFront(patterSelector)
i++
}
您还必须确保userInteractionEnabled
中的true
为decorationBg
,否则不会传播到您的图片视图
答案 1 :(得分:0)
(1)如何在循环中创建与数据绑定的出口?
如果要绑定String数据,请尝试accessibilityLabel
属性。你可以设置&无声地检索价值。
(2)为什么跟随的UITapGestureRecoginzer根本不起作用?
您错过了启用userInteractionEnabled
UIImageView
希望这会对你有所帮助。