Change button text inside segment control

2.2k views Asked by At

I have segment control and code like this in .m file

-(IBAction)sectionswitch:(id)sender {

    if (control.selectedSegmentIndex == 0) {
        UIImage *dekabristov = [UIImage imageNamed:@"dekabristov.png"];
        [image setImage:dekabristov];
    }

    if (control.selectedSegmentIndex == 1) {
        UIImage *fabrika = [UIImage imageNamed:@"fabrika.jpg"];
        [image setImage:fabrika];
    }

}

How i can change title of action button inside segment control? If i write [button setTitle:@"Button!"]; Xcode says "Use undeclared identifier "button", but -(IBAction)button:(id)sender; in .h file

4

There are 4 answers

0
Ilario On BEST ANSWER

in that way, you have not declared a button, but only an action called 'button'.

in your .h file you should do:

 @interface yourViewController : UIViewController {

   UIButton *button;

 }

and for change title of segment control you can do:

 [yourSegmentControl setTitle:@"Button!" forSegmentAtIndex:0]; //0 is the first

if you want change a title of an UIButton:

[button setTitle:@"Title" forState: UIControlStateNormal];
2
AXE On

If I got you right you want to change dynamically the title of the segments. You can do this with UISegmentedControl's method

- (void)setTitle:(NSString *)title forSegmentAtIndex:(NSUInteger)segment

You will need to have an outlet property of the segment control in your xib file. Then you just do this:

[self.mySegmentControl setTitle:@"New title" forSegmentAtIndex:0];
2
Haresh Ghatala On

- (IBAction)button:(id)sender; is a Method not Identifier

so for change title Text of Action button you have to write following code

-(IBAction)sectionswitch:(id)sender {

    if (control.selectedSegmentIndex == 0) {
        ...
        [sender setTitle:@"AAAAA" forSegmentAtIndex:0];
        ...
    }

    if (control.selectedSegmentIndex == 1) {
        ...
        [sender setTitle:@"BBBBB" forSegmentAtIndex:1];
        ...
    }

}
0
Ahmadreza On

Swift 4

    segmentButton.setTitle("hello", forSegmentAt: 0)