【问题标题】:Change UISegmentedControl titles programmatically以编程方式更改 UISegmentedControl 标题
【发布时间】:2012-05-17 22:33:59
【问题描述】:

如何以编程方式更改 UISegmentedControl 标题?你能帮帮我吗?

@synthesize filterControl; //UISegmentedControl

- (void)viewDidLoad
{
    [super viewDidLoad];

    filterControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"ALL",@"PROFIT",@"LOSS", nil]]; //not working

}

【问题讨论】:

    标签: objective-c xcode uisegmentedcontrol


    【解决方案1】:

    Swift5

    要更改 HmSegment 控件的标题字体和大小,您必须使用 titleTextAttributes 属性。

    segmentedControl.titleTextAttributes = [NSAttributedString.Key.font: UIFont(name: "Poppins-Medium", size: 16.0) as Any]
    segmentedControl.setNeedsDisplay()
    

    【讨论】:

      【解决方案2】:

      更新:

      使用下面的简单代码以编程方式设置 UISegmentControl 标题;

      - (void)viewDidLoad {
      
          [super viewDidLoad];
      
           [self.segmentControl setTitle:@"Love It" forSegmentAtIndex:0];
           [self.segmentControl setTitle:@"Hate It" forSegmentAtIndex:1];        
           [self.segmentControl setTitle:@"Ehh" forSegmentAtIndex:2];
      }
      

      // 注意:这里self.segmentControl = filterControl

      【讨论】:

        【解决方案3】:

        您可以直接更改sectionTitles

        经常错过的是致电setNeedsDisplay()

        Swift 中的代码:

        segmentedControl.sectionTitles = ["All", "Profit", "Loss"]
        segmentedControl.setNeedsDisplay()
        

        【讨论】:

        • 不适用于 Swift 5。没有像 .sectionTitles 这样的功能
        【解决方案4】:
         [filterControl setTitle:@"All" forSegmentAtIndex:0];
         [filterControl setTitle:@"PROFIT" forSegmentAtIndex:1];
         [filterControl  setTitle:@"LOSS" forSegmentAtIndex:2];
        

        试试这个。希望它对你有用。

        【讨论】:

          【解决方案5】:

          随便用

          -setTitle:(NSString*)title forSegmentAtIndex:(NSUInteger)index;
          

          【讨论】:

            【解决方案6】:

            您是否已将 filterControl 作为子视图添加到其父视图中?

            【讨论】:

            • 我已经手动添加了,它工作正常。只有我需要以编程方式更改这些标题。你能帮帮我吗?
            • 使用这个 API - (void)insertSegmentWithTitle:(NSString *)title atIndex:(NSUInteger)segment animated:(BOOL)animated;
            • 当使用此代码时,它会插入一个新的,如何删除现有的段?
            • 谢谢你,Allamarabhu,我已经修复了这样的问题:[filterControl removeAllSegments]; [filterControl insertSegmentWithTitle:@“1”atIndex:0动画:NO]; [filterControl insertSegmentWithTitle:@“2”atIndex:0动画:NO];
            猜你喜欢
            • 1970-01-01
            • 2012-07-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多