1

我是 iOS 开发的新手,我对UIScrollView. 首先,我在情节提要中创建了一个滚动视图并添加了

@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 的情节提要上添加一个按钮,则会出现该按钮并且我可以滚动视图。

如何在代码中添加按钮?

4

5 回答 5

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];
于 2013-09-19T09:41:04.343 回答
1

boundsframe不是一回事。

请改用此代码...

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"Hello" forState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, 100, 44);
[self.mainScroll addSubview:button];
于 2013-09-19T09:41:58.187 回答
1

您需要设置滚动视图内容大小,类似于以下代码。

[self.mainScroll setContentSize:CGSizeMake(width, height)];
于 2015-02-13T14:46:48.980 回答
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];
于 2013-09-19T09:49:21.087 回答
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


}
于 2013-09-19T10:21:52.153 回答