2014-02-24 44 views
9

当我为分段控件设置自定义字体时,它会更改垂直文本对齐方式。我正在使用下面的代码来设置字体。设置自定义字体时的文本对齐问题

// I dont think these lines are creating any issue but just wanted to paste all the code 
    self.segmentType.layer.borderColor = navigationTintColor.CGColor; 
    self.segmentType.layer.cornerRadius = 0.0; 
    self.segmentType.layer.borderWidth = 1.5; 

    // These are the lines that are changing the text alignment 
    UIFont *font = [UIFont fontWithName:ftHelveticaNeueLTPro_Th size:13.5];   
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:font 
                  forKey:UITextAttributeFont]; 
    [self.segmentType setTitleTextAttributes:attributes 
            forState:UIControlStateNormal]; 

下面是最新情况的截图。如果你是观察者,文本不是垂直居中对齐。

enter image description here

请帮帮我。先谢谢你 !!

+0

那么当你使用另一种字体(比如标准的iOS)会发生什么?而当你不使用分数字体大小时会发生什么? – bilobatum

+0

@bilobatum如果我使用默认字体,那么文本对齐是完美的。我也尝试将字体大小更改为不同的值,但没有运气,对齐方式不正确。 –

+0

您可以尝试设置文本的背景颜色,并查看文本上方和下方占用的空间量吗?字体可能会在文本上方和/或下方使用一些额外的空白。 –

回答

12

@Emmanuel建议的以下代码完美无缺。您可以更改垂直偏移以在中心垂直对齐文本。

[self.segmentType setContentPositionAdjustment:UIOffsetMake(0, 2) forSegmentType:UISegmentedControlSegmentAny barMetrics:UIBarMetricsDefault]; 
+1

如果您需要针对应用中所有分段控件的全局解决方案,可以在AppDelegate中为[SegmentType:UISegmentedControlSegmentAny barMetrics:UIBarMetricsDefault]设置[ – Alex

+0

或者您可以将此代码放在UISegmentedControl的自定义子类的drawrect方法内,在这种情况下,您只需说'self'而不是'self.segmentType'。 – CommaToast

0

你可以在自定义视图上使用自定义UILabel来尝试使用它。根据实际视图的便利性,更改&修改titleLabel或customSegmentView的帧值。并将此全视图作为子视图添加到您的分段控件中。

UIView *customSegmentView = [[UIView alloc] init]; 
    UILabel *segmentTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 7.0f,180.0f,22.6f)]; 
    segmentTitleLabel.text = @"your-text";  
    segmentTitleLabel.backgroundColor = [UIColor clearColor]; 
    segmentTitleLabel.textAlignment = UITextAlignmentCenter; 
    segmentTitleLabel.font = [UIFont fontWithName:@"ftHelveticaNeueLTPro_Th" size:13.5f]; 
    customSegmentView.frame = CGRectMake(60, 20, 180, 35); 
    [customSegmentView addSubview:segmentTitleLabel]; 
    [self.segmentType setTitleView:customSegmentView]; 

希望能够解决您的问题。请检查并告诉我们是否需要使用其他解决方案。

0

在的InterfaceBuilder的XCode中6存在用于所述段,这会影响文本的基线一个内容偏移控制。我有这个问题,因为我的内容偏移在Y维度上是2而不是0.