我创建了一个很酷的应用程序,它以编程方式创建了 50 多个,UIButtons
包括一个动作选择器。动作(播放声音)从 3 日UIView
起停止工作。
在UIView
里面UIScrollView
并且使用分页。
我使用 iOS 5,但我认为这不是问题。此外,声音在UIScrollView
. 此外,如果我更改按钮的数量(或多或少),声音总是很有吸引力,直到我到达第 3 页:/
这里的代码:
- (void)setButtons
{
int screenWidth = 320;
int screenHeight = 410;
int rows = krows;
int cols = kcols;
int marginLeft = kmarginLeft;
int height = kheight;
int buttonWidth = kbuttonWidth;
int buttonHeight = kbuttonHeight;
int delta = kdelta; // gap between buttons
int startPosY = kstartPosY;
int startPosX = kstartPosX;
int posY = startPosY;
int posX = startPosX;
int contentWidth = screenWidth;
int intStart = 0;
NSMutableDictionary *dict = [Persistence getDictFromParam:@"Bud"];
NSArray *keys = [dict allKeys];
// sort keys
NSArray *sortedKeys = [keys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
int len = keys.count; //50;
NSLog(@"len: %d", len);
CGSize scrollViewContentSize = CGSizeMake(screenWidth, screenHeight);
[scrollView setContentSize:scrollViewContentSize];
for( int i = intStart; i < len; i++ ) {
UIButton* aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton addTarget:self action:@selector(sound1Action:) forControlEvents:UIControlEventTouchUpInside];
NSString *key = [sortedKeys objectAtIndex:i];
if (i > 0) {
posY += delta + height;
int mod = i % rows;
if(mod == 0) {
int mod2 = i % (rows*cols);
if(mod2 == 0) {
posX += marginLeft;
}
posX += (marginLeft + buttonWidth);
// extend pages
if(posX > contentWidth) {
contentWidth += screenWidth;
CGSize scrollViewContentSize = CGSizeMake(contentWidth, screenHeight);
[scrollView setContentSize:scrollViewContentSize];
}
posY = startPosY;
}
}
[aButton setFrame:CGRectMake(posX, posY, buttonWidth, buttonHeight)];
NSString *title = [[NSString alloc] initWithFormat:@"%@", key];
[aButton setBackgroundImage:[UIImage imageNamed:@"button_normal.png"] forState:UIControlStateNormal];
[aButton setBackgroundImage:[UIImage imageNamed:@"button_pushed.png"] forState:UIControlStateHighlighted];
[aButton setBackgroundImage:[UIImage imageNamed:@"button_pushed.png"] forState:UIControlStateSelected];
[aButton setTitle:title forState:UIControlStateNormal];
[aButton setTag:i];
NSLog(@"%@: %d",title, aButton.tag);
[contentView addSubview:aButton];
}
[scrollView setPagingEnabled:YES];
}
- (void)sound1Action:(id)sender {
UIButton *button = (UIButton*)sender;
int i = button.tag;
BackgroundMusic *backgroundMusic = [BackgroundMusic sharedInstance];
NSArray *sortedKeys = [self sortedDict];
NSString *val = [[self getDict] objectForKey:[sortedKeys objectAtIndex:i]];
NSLog(@"%@",val);
NSURL *url = [[NSBundle mainBundle] URLForResource:val withExtension:nil];
NSString *pathUrl = [url path];
backgroundMusic.player=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:pathUrl] error:NULL];
[backgroundMusic.player stop];
[backgroundMusic.player play];
[backgroundMusic player].volume = 0.5;
backgroundMusic.player.numberOfLoops = 0; //-1; initite
}