[英]How to add a button to a UIScrollView as a subView from outside the same method?
So I am trying to get a simple UIScrollView working with a bunch of buttons. 因此,我正在尝试使用一个简单的UIScrollView和一堆按钮。 I was successfully able to accomplish this task with the following code:
我可以使用以下代码成功完成此任务:
- (void)viewDidLoad
{
[super viewDidLoad];
[_scroller setScrollEnabled:YES];
[_scroller setContentSize:CGSizeMake(320, 1487)];
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -500, 320, 2800)];
[imgView setBackgroundColor:[UIColor blackColor]];
[_scroller addSubview:imgView];
UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn1 setTitle:@"Cool title" forState:UIControlStateNormal];
[btn1 setFrame:CGRectMake(7, 7, 150, 160)];
[btn1 setImage:[UIImage imageNamed:@"small.png"] forState:UIControlStateNormal];
[btn1 addTarget:self action:@selector(btn1_m) forControlEvents:UIControlEventTouchUpInside];
[_scroller addSubview:btn1];
However, what if I to add buttons through interface builder instead of programmatically adding them? 但是,如果我通过界面生成器添加按钮而不是通过编程方式添加按钮怎么办? Whenever I do this, the scroller no longer scrolls!
每当我这样做时,滚动条就不再滚动!
For example, if I use the following code after control-dragging a button: 例如,如果我在按住Control并拖动按钮后使用以下代码:
- (IBAction)theButton:(UIButton *)sender {
[_scroller addSubview:sender];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[_scroller setScrollEnabled:YES];
[_scroller setContentSize:CGSizeMake(320, 1487)];
}
...The scroll doesn't work, I see the button but nothing scrolls anymore. ...滚动不起作用,我看到该按钮,但没有任何滚动。 Basically, I just want to use interface builder to add buttons to my app and have them scroll too, but can't seem to get this to work!
基本上,我只想使用界面生成器将按钮添加到我的应用程序中,并使它们也滚动,但似乎无法使它正常工作!
When you create your UI programmatically, the subviews of your scrollview are like this: 以编程方式创建UI时,滚动视图的子视图如下所示:
ImageView
影像检视
Button纽扣
Button纽扣
......
When you use IB to add your buttons, you end up with this: 当您使用IB添加按钮时,您将得到以下结果:
Button
纽扣
Button纽扣
......
ImageView影像检视
Place a breakpoint after your image view is added to the scroll view. 将图像视图添加到滚动视图后,放置一个断点。 In the LLDB console type:
在LLDB控制台中,输入:
(lldb) po _scroller.subviews
(lldb)po _scroller.subviews
I suspect you will see your image view at the bottom of the list. 我怀疑您会在列表底部看到图像视图。 It is covering your buttons, but it is scrolling, it just doesn't look like it as it is a large black image view.
它覆盖了您的按钮,但是却在滚动,它看起来像不是很大,因为它是一个大的黑色图像视图。
Send your image view to the back of the subview list: 将图像视图发送到子视图列表的后面:
[_scroller sendSubviewToBack:imgView];
[_scroller sendSubviewToBack:imgView];
Then you will see your buttons again. 然后,您将再次看到您的按钮。 Also, after you have done this, confirm your scrollview content size in lldb:
另外,完成此操作后,请在lldb中确认您的scrollview内容大小:
(lldb) p _scroller.contentSize
(lldb)p _scroller.contentSize
If it all looks correct, it should be scrolling. 如果一切看起来正确,则应该正在滚动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.