2011-04-13 2 views

답변

23

헤더 파일에서 39 개의 버튼을 제외하고 단일 배열을 사용하고자 할 수 있습니다. 인터페이스 빌더를 사용하여 이벤트 및 레이아웃을 제어 할 수 있도록 수동 참조를 사용하려고합니다. 나는 조금 다른 것을하는 것이 좋습니다.

단일 속성 - NSMutableArray을 만듭니다. 그런 다음보기가로드되면 즉시 버튼을 만듭니다.

버튼에 액세스하려면 [self.arrayOfButtons objectAtIndex:38];과 같은 것을 사용하십시오. (39 개 버튼의 경우, 그 마지막 버튼을 반환합니다.)`

가 버튼을 만들려면 다음을 사용 : 당신이 당신의 버튼의 init의 프레임을 전달

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; 

주 방법. 버튼의 프레임은 컨테이너의 왼쪽 상단에서 시작하며 버튼은 100 픽셀 정사각형입니다. 프레임은 CGRect의 인스턴스입니다. (당신은 기능 CGRectMake(x,y,width,height)를 호출하여 CGRect을 만들

39 개 버튼을 만들려면 다음과 같이 루프를 할 수 있습니다, 배열을 지정해, 버튼, myButtons 미리 정의 된 numberOfButtons 및 치수 변수 잡아 :.

for(int i=0;i<numberOfButtons;i++){ 
    //Create the button 
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x,y,width, height)]; 
    //Store the button in our array 
    [self.myArray addObject:button]; 
    //Release the button (our array retains it for us) 
    [button release]; 
} 

물론, 각 버튼에 대해 x, y, widthheight에 대해 고유 한 값을 설정해야합니다. 버튼을 만들면 라벨 설정과 같은 작업을 수행 할 수 있습니다. 화면에 표시하십시오.화면이 쓸모가 그냥 버튼을 추가, 물론

for(UIButton *button in self.myButtons){ 
    //add the button to the view 
    [self.view addSubview:button]; 
} 

: 화면을 표시하려면, 당신은 이런 식으로 뭔가를 할 수 있습니다. 당신은 그들에게 뭔가를 할 수 있어야합니다. 버튼에 액션을 추가하려면, 당신은 사용할 수 있습니다

[button addTarget:self action:@selector(someMethod:) forControlEvents:UIControlEventTouchDown]; 

첫 번째 부분, addTarget:self을,이 뷰 컨트롤러는 처리를 요청하는거야 이벤트를 처리 말한다. action:@selector(someMethod:)은 이벤트가 발생할 때 수행 할 메소드를 클래스에 알립니다. 그런 다음 forControlEvents:UIControlEventTouchDown은 버튼이 탭 될 때 해당 클래스가 상기 메소드를 수행해야한다고 말합니다.

그래서, 당신의 헤더 :

#import <UIKit/UIKit.h> 

@interface MyClass :UIViewController{ 

    NSMutableArray *myButtons; 
} 

@property (nonatomic, retain) NSMutableArray *myButtons; 

//Use UIButton as the sender type if you want 
- (void)someMethod:(id)sender; 

// ... Other code can go here of course 
@end 

그리고 구현에, 당신이 사용할 수 있습니다

#import MyClass.h 


@implementation MyClass 

- (id)init{ 

    self = [super init]; 

    if(self){ 

    NSMutableArray *temp = [[NSMutableArray alloc] init]; 
    self.myButtons = temp; 
    [temp release]; 

    } 

    return self; 

} 


- (void)viewDidLoad{ 

    // 
    // Create the buttons 
    // 

    for(int i=0;i<numberOfButtons;i++){ 
    //Create the button 
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x,y,width, height)]; 

    //You may want to set button titles here 
    //or perform other customizations 

    //Store the button in our array 
    [self.myArray addObject:button]; 
    //Release the button (our array retains it for us) 
    [button release]; 
    } 

    // 
    // Show the buttons onscreen 
    // 

    for(UIButton *button in self.myButtons){ 
    //add the button to the view 
    [self.view addSubview:button]; 
    //add the action 
    [button addTarget:self action:@selector(someMethod:) forControlEvents:UIControlEventTouchDown]; 
    } 
} 

- (void)someMethod:(id)sender{ 
    //Do something when the button was pressed; 
} 

- (void)dealloc{ 
    [self.myButtons release]; 
    [super dealloc]; 
} 

@end 

을 지금, 당신은 인터페이스 빌더를 복용하지 않고 버튼 천국에 갈 수 비행기에. UIButton 행복하게 가십시오!

+1

정말 멋진 접근 !! UIScrollView를 사용하고 있으므로 프레임을 설정하는 것이 처음에는 어려울 것입니다. 이것에 시간을 할애 해 주셔서 대단히 감사합니다. 정말 고맙습니다! –

+2

감사. 사실 UIScrollView에서 프레임을 설정하는 것은 그렇게 어렵지 않습니다. UIScrollView에는 contentSize라는 속성이 있습니다. 프레임은 상위 뷰의 프레임을 기반으로합니다. 스크롤보기에 추가하기 만하면됩니다. – Moshe

+0

또한 foreach 메서드가 objective-c에 존재하지 않습니다. –

2

Key Value programming 당신의 친구 기본적으로 당신이 주변에 루프 수와 버튼을 생성하고 당신이 당신의 버튼에 대해 정의 된 특성을 가지고

입니다 너는 할 수있어.

[self setObject:newButton [email protected]"button1"]; 

여기서 button1은 변수 이름과 동일한 문자열입니다.

9

과 같이 : [자기 valueForKey :]

NSMutableArray *arr = [NSMutableArray array]; 
for(int i = 1; i <= 39; ++i) { 
    [arr addObject:[self valueForKey:[NSString stringWithFormat:@"btn%d", i]]]; 
} 
+0

야곱, 안녕하세요. – Moshe

+0

@Moshe 감사합니다! :) –

3

당신은 게터 각 버튼 후 전화보다라는 방법을 만들 수 있습니다; 여기서 뭔가 있지만, 각 단지 "끔찍한 디자인을"비명 소리에 대한 :)

+0

전적으로 동의합니다. 뭔가 냄새가 난다. –

4
for(int i=1; i<totalButtonCount; i++) { 
    NSString *buttonClassName = [NSString stringWithFormat:@"btn%d", i]; 
    [[NSClassFromString(buttonClassName) alloc] init]; 
    //add to array 
} 

편집 : 질문을 다시 읽고, 이것은 당신이 요구하는지 무엇을하지 않을 수 있습니다. 비슷한 클래스의 인스턴스를 많이 만들고 싶다고 생각했습니다.

+0

예, 분명합니다. 내 대답을 읽었 니? –

+0

Scheriman이 편집 전에 댓글을 썼을 가능성이 있습니까? :) –

+0

나는 그것을 즉시 만들었다. 사장님, 제 이전 톤은 어제 스트레스를 많이 받았습니다. ;) –

관련 문제