не в состоянии изменить свойство объектов NSArray - PullRequest
0 голосов
/ 13 августа 2011

У меня есть:

@property(nonatomic, retain) NSArray * buttonsArray;

...
...
@synthesize buttonsArray;

при загрузке представления. Я инициализирую его следующим образом:

buttonsArray = [[NSArray alloc] initWithObjects:
                             [UIButton buttonWithType:UIButtonTypeRoundedRect],
                             [UIButton buttonWithType:UIButtonTypeRoundedRect], 
                             [UIButton buttonWithType:UIButtonTypeRoundedRect], 
                             [UIButton buttonWithType:UIButtonTypeRoundedRect], 
                             [UIButton buttonWithType:UIButtonTypeRoundedRect], 
                             [UIButton buttonWithType:UIButtonTypeRoundedRect],
                             [UIButton buttonWithType:UIButtonTypeRoundedRect], 
                             [UIButton buttonWithType:UIButtonTypeRoundedRect], 
                             [UIButton buttonWithType:UIButtonTypeRoundedRect], 
                             [UIButton buttonWithType:UIButtonTypeRoundedRect], 
                             [UIButton buttonWithType:UIButtonTypeRoundedRect],
                             [UIButton buttonWithType:UIButtonTypeRoundedRect], 
                             [UIButton buttonWithType:UIButtonTypeRoundedRect], 
                             [UIButton buttonWithType:UIButtonTypeRoundedRect], 
                             [UIButton buttonWithType:UIButtonTypeRoundedRect], 
                             [UIButton buttonWithType:UIButtonTypeRoundedRect],
                             [UIButton buttonWithType:UIButtonTypeRoundedRect], 
                             [UIButton buttonWithType:UIButtonTypeRoundedRect], 
                             [UIButton buttonWithType:UIButtonTypeRoundedRect], 
                             [UIButton buttonWithType:UIButtonTypeRoundedRect], 
                             [UIButton buttonWithType:UIButtonTypeRoundedRect],
                             nil];

// этот код помещает кнопки из массива кнопок поверх изображений вмой взгляд.Я поместил эти изображения в массив с именем imagesArrayV;

int counter = 0;


    counter=0;
    for (UIButton *button in buttonsArray) {

        button = [buttonsArray objectAtIndex:counter];
        [button setTag:counter]; // *********
        button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchDown];
        [button setTitle:@"Hello" forState:UIControlStateNormal];

        UIImageView *tempImage = [imagesArrayV objectAtIndex:counter];
        CGRect tempRect = tempImage.frame;
        button.frame = tempRect;

        [self.ViewMainV addSubview:button];
        counter++;
    } 

. Цель этого - сэкономить время, создавая все кнопки в xcode и создавая соединения.

enter image description here

Я разместил картинку, чтобы вы могли получить представление ...

В любом случае метод, который выполняется при нажатии кнопки:

-(void) test: (id) sender{


    UIButton*btn = (UIButton*)(sender);


    int tagnumber = [btn tag];

    NSLog(@"%i",tagnumber);

}

почему при нажатии на кнопку тэг равен 0, когда я настраиваю его на что-то другое (ищите: // *********) при создании кнопки.Более того, когда я запускаю этот метод:

-(void) someOtherMethod{
    int counter = 0;
    for (UIButton *button in buttonsArray) {
        button = [buttonsArray objectAtIndex:counter];
        button.alpha = 0;
        button.titleLabel.text = @"I change the title";
        counter++;
    }
}

кнопки, которые я ранее добавил, не меняются вообще.также альфа не меняется.Я не знаю, какую кнопку я меняю, когда запускаю последний метод.

Ответы [ 3 ]

4 голосов
/ 13 августа 2011

Чуть ниже линии, где вы устанавливаете тег, у вас есть строка button = [UIButton buttonWithType:UIButtonTypeRoundedRect];.Это перезаписывает кнопку, очевидно.Затем добавляется действие к вновь созданной кнопке, кнопки в массиве остаются без изменений.

Лично я бы переписал код следующим образом:

for (int counter = 0; counter < numberOfButtons; ++counter) {
    button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setTag:counter];
    [button addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchDown];
    [button setTitle:@"Hello" forState:UIControlStateNormal];

    UIImageView *tempImage = [imagesArrayV objectAtIndex:counter];
    CGRect tempRect = tempImage.frame;
    button.frame = tempRect;

    [self.ViewMainV addSubview:button];
    [buttonsArray addObject:button];
} 

Это также позволяет избежать заполнения массиважестко закодированный, для более гибкого, менее подверженного ошибкам кода.

0 голосов
/ 13 августа 2011

Это выглядит подозрительно, и вы делаете это дважды:

for (UIButton *button in buttonsArray) {

    button = [buttonsArray objectAtIndex:counter];

Не следует изменять кнопку переменной перечисления цикла внутри цикла.Вы просто используете кнопку как есть.

IOW, вы либо делаете:

for (counter = 0; counter < buttonsArray.count; counter++) 
{
    UIButton *button = [buttonsArray objectAtIndex: counter];
    button.alpha = 0;
    // etc...

, либо просто избавляетесь от counter и делаете:

for (UIButton * button in buttonsArray) 
{
    button.alpha = 0;
    // etc... 
0 голосов
/ 13 августа 2011

попробуйте использовать этот код вместо третьего раздела выше:

for(int i=0;i<[buttonsArray count];i++){
    UIButton *button=[buttonsArray objectAtIndex:i];
    [button addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchDown];
    [button setTitle:@"Hello" forState:UIControlStateNormal];

    UIImageView *tempImage  = [imagesArrayV objectAtIndex:counter];
    button.frame            = tempImage.frame;
    button.tag              =i;
    [self.ViewMainV addSubview:button];
}

Одна из проблем заключается в том, что вы устанавливали тег для кнопки, а затем заменяли экземпляр кнопки на следующей строке.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...