简体   繁体   English

细分的 UISegmentedControl 自定义图像

[英]UISegmentedControl custom image for segment

有什么方法可以为 UISegmentedcontrol 中的选定段设置自定义图像并更改字体大小?

Use the below code in UIControlEventValueChanged event targetUIControlEventValueChanged事件目标中使用以下代码

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+请注意,这仅适用于 iOS5+

swift 5.x for changing Image:用于更改图像的 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)

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM