你怎么用swift写这个?我在翻译时遇到了麻烦,因为swift是我的第一语言,这都是用Objective C编写的。
UIScrollView * scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * 3, scrollView.frame.size.height);
scrollView.delegate = self;
UIPageControl * pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 90, scrollView.frame.size.width, 20)];
pageControl.numberOfPages = scrollView.contentSize.width/scrollView.frame.size.width;
[pageControl addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged];
Then you need to add the following two methods:
- (IBAction)changePage:(id)sender {
CGFloat x = pageControl.currentPage * scrollView.frame.size.width;
[scrollView setContentOffset:CGPointMake(x, 0) animated:YES];
}
-(void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
NSInteger pageNumber = roundf(scrollView.contentOffset.x / (scrollView.frame.size.width));
pageControl.currentPage = pageNumber;
答案 0 :(得分:6)
首先要做的事情 - 我强烈建议您阅读有关Swift和Objective-C互操作性的资源。有关详细信息,请参阅https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/。
斯威夫特是一种用它自己的成语的语言。 Objective-C代码可以以各种方式转换为它们。例如,在使用Objective-C中的对象时必须使用指针,这隐式地使得可以使用nil
引用。 Swift使用可选类型来表达,因此UIScrollView * scrollView
可以转换为let scrollView : UIScrollView
或let scrollView : UIScrollView?
,具体取决于上下文。
当然,这只是一个冰山一角。根据上下文进行的翻译可能会发生变化,因此在开始迁移代码之前,最好先学习和理解基本的Swift。
好的,既然我们现在已经清楚了,那就是翻译:
let scrollView = UIScrollView(frame: CGRectMake(0, 0, 100, 100))
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * 3, scrollView.frame.size.height)
scrollView.delegate = self
let pageControl = UIPageControl(frame:CGRectMake(0, 90, scrollView.frame.size.width, 20))
pageControl.numberOfPages = Int(scrollView.contentSize.width / scrollView.frame.size.width)
pageControl.addTarget(self, action: Selector("changePage:"), forControlEvents: UIControlEvents.ValueChanged)
func changePage(sender: AnyObject) -> () {
let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
scrollView.setContentOffset(CGPointMake(x, 0), animated: true)
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) -> () {
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width);
pageControl.currentPage = Int(pageNumber)
}