通过UIView中的UIImageViews循环 - Swift

时间:2015-10-10 13:44:00

标签: ios swift uiview uiimageview swift2

我一直试图在Swift中做一些与下面的代码示例(Objective C)非常相似的东西。是否有人能够提供下面显示的函数的Swift实现或类似的东西?

- (UIImageView *) getSectorByValue:(int)value {
UIImageView *res;
NSArray *views = [container subviews];
for (UIImageView *im in views) {
    if (im.tag == value)
        res = im;
}
return res;

}

3 个答案:

答案 0 :(得分:1)

这是Swift中的类似实现:

func getSectorByValue(value: Int) -> UIImageView? {
    for subView in container.subviews {
        if subView.tag == value {
            return subView as? UIImageView
        }
    }
    return nil
}

答案 1 :(得分:0)

这样的事情应该有效。

func getSectorByValue(value: Int) -> UIImageView? {
    let views = container.subviews() 
    if let i = views.indexOf({$0.tag == value}) {
        return views[i] as? UIImageView
    }
    return nil
}

答案 2 :(得分:0)

循环虽然手动的子视图是不必要的复杂。

有一个UIView方法viewWithTag可以通过一行代码获取所需的视图:

func getSectorByValue(value: Int) -> UIImageView? 
{
    return container.viewWithTag(value) as? UIImageView
}
相关问题