从Objective-C转换后,我在Swift中面临问题。任何人都可以帮我解决这个问题吗?
var panels = NSArray?
func buttonTotalWidth() -> CGFloat {
var width: CGFloat = 0
for panel: UIView? in panels {
width += panel?.frame.width
}
return width
}
我的目标C代码
@property NSArray *panels;
- (CGFloat)buttonTotalWidth {
CGFloat width = 0;
for (UIView *panel in self.panels) {
width += CGRectGetWidth(panel.frame);
}
return width;
}
答案 0 :(得分:4)
请不要尝试将ObjC代码字面翻译为Swift。学习Swift特定的东西。
swifty 翻译可能是
var panels = [UIView]()
func buttonTotalWidth() -> CGFloat {
return panels.map{$0.frame.width}.reduce(0.0, + )
}
答案 1 :(得分:0)
此方法接受UIView数组(而不是可选的UIVIew),试试这个
var panels = self.view.subviews
var width = buttonTotalWidth(panels)
func buttonTotalWidth(_ panels: [UIView]) -> CGFloat {
var width: CGFloat = 0
for panel: UIView in panels.enumerated() {
width += panel.frame.width
}
return width
}
如果这些是可选的UIViews,试试这个,
func buttonTotalWidth(_ panels: [UIView?]) -> CGFloat {
var width: CGFloat = 0
for panel: UIView? in panels.enumerated() {
width += panel?.frame.width
}
return width
}