如何以编程方式创建UIScrollView?

Eth*_*ick 38 iphone objective-c uiscrollview

好吧,所以这里的关键是我根本不使用IB,因为我正在使用的View是以编程方式创建的.该UIView覆盖下半部分的屏幕,并有一堆上的按钮.但是,我想添加更多按钮UIView,而不是更大.为此,我想UIScrollView在视图内部进行操作,这将允许我在屏幕上添加更多按钮,以便用户可以滚动到它们.我认为这是它的工作原理.

self.manaView = [[[UIView alloc] initWithFrame:frame] autorelease];
self.manaView.backgroundColor = [UIColor purpleColor];

UIScrollView *scroll = [UIScrollView alloc];
scroll.contentSize = CGSizeMake(320, 400);
scroll.showsHorizontalScrollIndicator = YES;
[self.manaView addSubview:scroll];
Run Code Online (Sandbox Code Playgroud)

代码的第一部分引用了我的UIView,它工作得很好,但我无法弄清楚如何以UIScrollView编程方式进行并将其添加到视图中,然后向其添加按钮.

UIButton *ret2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
ret2.tag = 102;
ret2.frame = CGRectMake(255, 5, 60, 50);
[ret2 setTitle:@"Return" forState:UIControlStateNormal];
[ret2 addTarget:self action:@selector(flipAction:) forControlEvents:UIControlEventTouchUpInside];
[scroll addSubview:ret2];
Run Code Online (Sandbox Code Playgroud)

当我这样做时,按钮就会从屏幕上消失.那么我该怎么做呢?谢谢您的帮助!

Ole*_*ann 26

代替:

UIScrollView *scroll = [UIScrollView alloc];
Run Code Online (Sandbox Code Playgroud)

这样做(将框架设置为你想要滚动视图的大):

UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:...];
Run Code Online (Sandbox Code Playgroud)


Ara*_*han 24

这可能对您以编程方式创建uiscrollview有所帮助
http://unconditionalloop.blogspot.com/2011/04/uiscrollview-programmatically.html

  UIScrollView *scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];   
     NSInteger viewcount= 4;  
     for(int i = 0; i< viewcount; i++) { 

        CGFloat y = i * self.view.frame.size.height;  
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, y,self.view.frame.size.width, self .view.frame.size.height)];       
        view.backgroundColor = [UIColor greenColor];  
        [scrollview addSubview:view];  
        [view release];  
     }    
  scrollview.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height *viewcount);   
  [self.view addSubview:scrollview];
Run Code Online (Sandbox Code Playgroud)

  • 我相信你还需要做`[self.view addSubview:scrollview];`它可以工作. (5认同)

NAN*_*NAV 12

试试这个,

{

        scrollview=[[UIScrollView alloc]initWithFrame:CGRectMake(0,0,320,480)]; 
        scrollview.showsVerticalScrollIndicator=YES;
        scrollview.scrollEnabled=YES;
        scrollview.userInteractionEnabled=YES;
        [self.view addSubview:scrollview];
        scrollview.contentSize = CGSizeMake(width,height);

    [scrollview release];
}
Run Code Online (Sandbox Code Playgroud)