如何使用 Xamarin 更改 iOS 中导航栏的标题字距调整值



我正在尝试调整导航栏中标题文本的字距调整。我已经将自定义UIStringAttributes分配给导航栏标题。设置字体和文本颜色似乎可以正常工作,但是当我输入字距调整时,无论我输入什么值,都不会发生任何事情。

public void SetTitleFont (string fontName, float fontSize, Color foregroundColor)
{
    var TitleAttr = new UIStringAttributes {
        ForegroundColor = foregroundColor.ToUIColor(),
        Font = UIFont.FromName (fontName, fontSize),
        KerningAdjustment = 50
    }; 
    this.NavigationController.NavigationBar.TitleTextAttributes = TitleAttr;
}

通了这个。

对我来说,解决问题的是创建一个新的UILabel,为UILabel设置属性,然后将TitleView设置为UILabel。

// We will grab the actual title of the Page further down.    
string viewTitle = string.Empty;
UINavigationItem navItem = new UINavigationItem();
if (this.NavigationController != null)
{
    if (this.NavigationController.VisibleViewController != null)
    {
        if (this.NavigationController.VisibleViewController.NavigationItem != null)
        {
            navItem = this.NavigationController.VisibleViewController.NavigationItem;
            // Grab the title of the Page you are on.
            if (navItem.Title != null)
            {
                viewTitle = this.NavigationController.VisibleViewController.NavigationItem.Title;
            }
        }
    }
}
// We do not want to set an arbitrary size for the UILabel.
// Otherwise, positioning it will be very difficult.
// The StringSize function will set the size of the UILabel to the absolute
// minimum size of whatever string you specify - given the correct
// parameters (font and fontSize).
CGSize titleSize = viewTitle.StringSize(UIFont.FromName (fontName, size));
// Create the new title UILabel. Make sure to set the Bounds!
pageTitleView = new UILabel {
    Bounds = new CGRect (0, 0, titleSize.Width, titleSize.Height),
    BackgroundColor = UIColor.FromRGBA(0, 0, 0, 0)
};
var titleAttributes = new NSAttributedString (viewTitle,
    new UIStringAttributes () {
    ForegroundColor =  foregroundColor.ToUIColor(),
    Font = UIFont.FromName (fontName, size),
    KerningAdjustment = 1.1f
});
// Apply the new attributes to the UILabel and center the text.
pageTitleView.AttributedText = titleAttributes;
pageTitleView.TextAlignment = UITextAlignment.Center;
// Set the TitleView to the new UILabel.
navItem.TitleView = pageTitleView;

我希望这有帮助!

最新更新