ios uiscrollview addsubview无法正常工作

时间:2013-09-19 09:37:23

标签: iphone ios objective-c uiscrollview addsubview

我是IOS开发的新手,但我遇到了UIScrollView的问题。首先,我在故事板中创建了Scroll View并添加了

@property (retain, nonatomic) IBOutlet UIScrollView *mainScroll;

在视图控制器处理程序

在viewDidLoad方法中,我有以下代码:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.mainScroll.contentSize = CGSizeMake(100.0,100.0); // Have to set a size here related to your content.
    // You should set these.
    self.mainScroll.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;



    self.mainScroll.minimumZoomScale = .5;  // You will have to set some values for these
    self.mainScroll.maximumZoomScale = 2.0;
    self.mainScroll.zoomScale = 1;

    UIButton* b = [[UIButton alloc] init];
    [b setBounds:CGRectMake(.0f,0.f,100.0,100.0)];
    [self.mainScroll addSubview:b];



}

但模拟器中没有任何内容。但是,如果我在IB的故事板上添加按钮,则会出现按钮,我可以滚动视图。

P.S。对不起我的语言

5 个答案:

答案 0 :(得分:6)

试试此代码

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self.mainScroll addSubview:button];

答案 1 :(得分:1)

boundsframe不是一回事。

请改用此代码......

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"Hello" forState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, 100, 44);
[self.mainScroll addSubview:button];

答案 2 :(得分:1)

您需要设置滚动视图内容大小,如下面的代码。

[self.mainScroll setContentSize:CGSizeMake(width, height)];

答案 3 :(得分:0)

试试这个:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"Hello" forState:UIControlStateNormal];
button.frame = CGRectMake(self.mainScroll.frame.origin.x + 25 ,self.mainScroll.frame.origin.y +25, 50, 44);
[self.mainScroll addSubview:button];

答案 4 :(得分:0)

从代码制作按钮的最佳和最简单的方法是:

    UIButton* yourButton = [[UIButton alloc]initWithFrame:CGRectMake(x, y, width, height)];
    [yourButton setTitle:@"Your Title" forState:UIControlStateNormal];

// if you set the button's image the title won't be visible, because button's title is "under" the image. I recomend you to use this if you have a cut and dried image.
    [yourButton setImage:[UIImage imageNamed:@"yourImage.png"] forState:UIControlStateNormal];

// if you set the button's background image, button's title will be visible 
    [yourButton setBackgroundImage:[UIImage imageNamed:@"yourBackgroundImage.png"] forState:UIControlStateNormal]; 

// you can add target to the button, for handle the event when you touch it.
    [yourButton addTarget:self action:@selector(handleToucUpInside:) forControlEvents:UIControlEventTouchUpInside]; 

// then add the button
    [self.view addSubview:yourButton];


- (void) handleToucUpInside:(id)sender{

    // here you can do anything you want, to handle the action


}