iOS基于UIScrollView实现滑动引导页
程序员文章站
2023-12-21 08:43:34
上代码前,我们先来看下实现的效果图:
welcomeviewcontroller.h
#import ...
上代码前,我们先来看下实现的效果图:
welcomeviewcontroller.h
#import <uikit/uikit.h> @interface welcomeviewcontroller : uiviewcontroller @end
welcomeviewcontroller.m
#import "welcomeviewcontroller.h" #define imagecount 3 @interface welcomeviewcontroller () <uiscrollviewdelegate> @property (nonatomic, strong)uipagecontrol *pagecontrol; @end @implementation welcomeviewcontroller - (void)viewdidload { [super viewdidload]; //创建scrollview uiscrollview *sv = [[uiscrollview alloc] init]; sv.frame = self.view.bounds; //设置边缘不弹跳 sv.bounces = no; //整页滚动 sv.pagingenabled = yes; sv.showshorizontalscrollindicator = no; //加入多个子视图(imageview) for(nsinteger i=0; i<imagecount; i++){ nsstring *imgname = [nsstring stringwithformat:@"%ld", i+1]; uiimage *image = [uiimage imagenamed:imgname]; uiimageview *imageview = [[uiimageview alloc]initwithimage:image]; cgrect frame = cgrectzero; frame.origin.x = i * sv.frame.size.width; frame.size = sv.frame.size; imageview.frame = frame; [sv addsubview:imageview]; if(i==imagecount-1){ //开启图片的用户点击功能 imageview.userinteractionenabled = yes; //加个按钮 uibutton *button = [[uibutton alloc]init]; button.frame = cgrectmake((imageview.frame.size.width-150)/2, imageview.frame.size.height*0.8, 150, 40); button.backgroundcolor = [uicolor orangecolor]; [button settitle:@"立即体验" forstate:uicontrolstatenormal]; button.titlelabel.font = [uifont boldsystemfontofsize:16]; [imageview addsubview:button]; [button addtarget:self action:@selector(enter) forcontrolevents:uicontroleventtouchupinside]; } } sv.contentsize = cgsizemake(imagecount * sv.frame.size.width, sv.frame.size.height); [self.view addsubview:sv]; //加入页面指示控件pagecontrol uipagecontrol *pagecontrol = [[uipagecontrol alloc]init]; self.pagecontrol = pagecontrol; //设置frame pagecontrol.frame = cgrectmake(0, self.view.frame.size.height - 40, self.view.frame.size.width, 20); //分页面的数量 pagecontrol.numberofpages = imagecount; //设置小圆点渲染颜色 pagecontrol.pageindicatortintcolor = [uicolor whitecolor]; //设置当前选中小圆点的渲染颜色 pagecontrol.currentpageindicatortintcolor = [uicolor redcolor]; //关闭用户点击交互 pagecontrol.userinteractionenabled = no; [self.view addsubview:pagecontrol]; sv.delegate = self; } - (void)enter { nslog(@"进入应用"); } //uiscrollviewdelegate方法 - (void)scrollviewdidscroll:(uiscrollview *)scrollview { cgpoint offset = scrollview.contentoffset; if(offset.x<=0){ offset.x = 0; scrollview.contentoffset = offset; } nsuinteger index = round(offset.x / scrollview.frame.size.width); self.pagecontrol.currentpage = index; } - (void)didreceivememorywarning { [super didreceivememorywarning]; // dispose of any resources that can be recreated. } @end
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。