从Objective C到Swift的Getter

时间:2014-07-23 05:17:26

标签: objective-c xcode5 swift getter

如何在Swift

中重新创建此getter代码
- (UIPageControl *)pageControl {
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] init];
        _pageControl.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
        _pageControl.frame = (CGRect){0, 35, CGRectGetWidth(self.bounds), 0};
        _pageControl.hidesForSinglePage = YES;
        _pageControl.currentPage = self.currentPage;
        _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
        _pageControl.pageIndicatorTintColor = [UIColor colorWithWhite:1.0 alpha:.5];
    } 
return _pageControl;
}

这就是我目前所拥有的

var pageControl: UIPageControl {
get{
    if (self.pageControl == nil) {
        var pageControl: UIPageControl= UIPageControl.alloc()
        pageControl.autoresizingMask = .FlexibleWidth | .FlexibleTopMargin;
        pageControl.frame = CGRectMake(0, 35, CGRectGetWidth(self.bounds), 0)
        pageControl.hidesForSinglePage = true;
        pageControl.currentPage = self.currentPage;
        pageControl.currentPageIndicatorTintColor = UIColor.whiteColor()
        pageControl.pageIndicatorTintColor = UIColor(white: 1.0, alpha: 0.5)
        return pageControl
    }
    return self.pageControl
}
}

但这不一样,因为它没有设置self.pageControl,如果我尝试添加此

self.pageControl = pageControl

我收到此错误“无法在'self'中分配'pageControl'”

3 个答案:

答案 0 :(得分:1)

你的财产有一个吸气剂,因此是一个计算属性'因此它没有一个二传手(除非你自己提供)。我怀疑你想要做的是用私有存储属性来支持你的计算属性:

private var _pageControl: UIPageControl?

var pageControl: UIPageControl {
get{
    // if the private backing variable doesn't exist, create it
    if (_pageControl == nil) {
        _pageControl = UIPageControl()
        // ...
    }
    return _pageControl
}
}

或者,请查看Lazy Stored Properties

答案 1 :(得分:0)

耶!这就是swift中getter的问题,你需要创建单独的方法来获取pageControl。

喜欢

func getPageControl() {

    if (self.pageControl == nil) {
        self.pageControl = UIPageControl.alloc()
         self.pageControl.autoresizingMask = .FlexibleWidth | .FlexibleTopMargin;
         self.pageControl.frame = CGRectMake(0, 35, CGRectGetWidth(self.bounds), 0)
         self.pageControl.hidesForSinglePage = true;
         self.pageControl.currentPage = self.currentPage;
         self.pageControl.currentPageIndicatorTintColor = UIColor.whiteColor()
         self.pageControl.pageIndicatorTintColor = UIColor(white: 1.0, alpha: 0.5)

    }
    return self.pageControl
}

希望这有帮助

答案 2 :(得分:0)

在这种只创建控件一次的情况下,您还可以使用lazy存储的属性,例如:

class MyClass {
    lazy var pageControl = MyClass.makePageControl()

    private class func makePageControl() -> UIPageControl {
        let pg = UIPageControl()
        pg.autoresizingMask = .FlexibleWidth | .FlexibleTopMargin;
        // …
        return pg
    }
}