Dipankar Choudhary
Dipankar Choudhary

Reputation: 11

Set the title for a button using number

I have a class numbers, and it has a property "randnum" which generates a random number. I want to set the title of a UIButton to this random number but its not working. Please point out a way to do it?

randnum property:-

    -(void)setRandnum:(NSString *)randnum
    {
        _randnum=randnum;
        NSArray *nums = @[@"0", @"1", @"2", @"3", @"4", @"5",@"6",@"7",@"8",@"9"];
        unsigned index=arc4random()%10;
        NSString* num = [NSString stringWithFormat:@"%@", [nums objectAtIndex:index]];
        _randnum=num;
    }

this is how i try to set the button title in ViewController:-

here numbers is a an outlet collection: @property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *numbers;

this is for UIButton in numbers;

    -(void)setNumbers:(NSArray *)numbers
    {
        _numbers=numbers;
        for (UIButton* button in self.numbers) {
            Number * number=[[Number alloc]init];
            [button setTitle:number.randnum forState:UIControlStateNormal];
        }
    }

Upvotes: 0

Views: 53

Answers (2)

Vishal Singh
Vishal Singh

Reputation: 4480

Looking at your code, you are not setting randnum anywhere, try below piece of code

-(void)setNumbers:(NSArray *)numbers
{
    _numbers=numbers;
    for (UIButton* button in self.numbers) {
        Number * number=[[Number alloc]init];
        [number setRandnum:nil];
        [button setTitle:number.randnum forState:UIControlStateNormal];
    }
}

However this doesn't seem to be the most appropriate way to achieve whatever your trying to achieve.

Upvotes: 0

Shahab Qureshi
Shahab Qureshi

Reputation: 950

why you need it as a class, why don't you use it as a function ? its simple random function. Use it as a function it will work.

If class is only solution don't override setter method. Just add it as a function. It will work. I tried both cases it is working fine.

Upvotes: 0

Related Questions