1

is there any way to set custom image for selected segment in UISegmentedcontrol and change the fontsize?

4

2 回答 2

3

Use the below code in UIControlEventValueChanged event target

I'm adding the sample code.

UISegmentedControl *segmentControl = [[UISegmentedControl alloc] init];
[segmentControl addTarget:self action:@selector(segmentedControlValueChanged:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:segmentControl];
[segmentControl release];
segmentControl = nil;


-(void)segmentedControlValueChanged:(UISegmentedControl *)selectedSegmentControl{

    int numSegments = [selectedSegmentControl.subviews count]; //getting the number of all segment sections

    //removing all segment section images.
    for( int i = 0; i < numSegments; i++ ) {

        [selectedSegmentControl setImage:nil forSegmentAtIndex:i];

    }       

    //setting image to the selected segment section.    
    [selectedSegmentControl setImage:[UIImage imageNamed:@"multiple.png"] forSegmentAtIndex:selectedSegmentControl.selectedSegmentIndex];

}

Please write down the details regarding the Font Size change . Do you wish to change only the selected segment text font size or for the all segment tabs?

Anyway, this is the common way to change the segment Font size. Please make use of it as per your conditions. You can add a comment below to get any additional help.

UIFont *myFont = [UIFont boldSystemFontOfSize:12.0f];
NSDictionary *myAttributes = [NSDictionary dictionaryWithObject:myFont
                                                       forKey:UITextAttributeFont];
[segmentedControl setTitleTextAttributes:myAttributes 
                                forState:UIControlStateNormal];

Please note that, this is only work with iOS5+

于 2012-07-02T16:17:13.027 回答
0

swift 5.x 用于更改图像:

  func addSegmented2(){

        let segmentedControl = UISegmentedControl(items: ["aa", "bb"])
        segmentedControl.frame = CGRect(x: 0, y: 240, width: 250, height: 30)
        self.view.addSubview(segmentedControl)
        let image = UIImage(named: "en")?.withRenderingMode(.**alwaysOriginal**)
        segmentedControl.setImage(image, forSegmentAt: 0)

    }
于 2020-04-19T14:19:00.023 回答