更改UISearchBar的字体大小

时间:2011-01-15 02:57:56

标签: ios objective-c uisearchbar uifont

如何更改UISearchBar的字体大小?

修改
答案

for(int i =0; i<[searchbar.subviews count]; i++) {
        if([[searchbar.subviews objectAtIndex:i] isKindOfClass:[UITextField class]])
            [(UITextField*)[searchbar.subviews objectAtIndex:i] setFont:[UIFont fontWithName:@"Helvetica" size:12]];
    }

感谢
的Pankaj

19 个答案:

答案 0 :(得分:149)

我建议iOS 5.0及更高版本使用不同的选项:

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setFont:[UIFont systemFontOfSize:14]];

for iOS 8(由Mike Gledhill链接):

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{
            NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:20],
      }];

适用于iOS 9及更高版本:

[[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setDefaultTextAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:20]}];

通过这种方式,您无需为应用中的每个搜索栏枚举子视图。

答案 1 :(得分:17)

执行此操作的安全方法如下:

for(UIView *subView in searchBar.subviews) {
    if ([subView isKindOfClass:[UITextField class]]) {
        UITextField *searchField = (UITextField *)subView;
        searchField.font = [UIFont fontWithName:@"Oswald" size:11];
    }
}

为什么这比接受的答案更安全?因为它不依赖于UITextField的索引保持不变。 (它也是循环清洁剂)

答案 2 :(得分:15)

UISearchBar里面有一个UITextField,但是没有属性可以访问它。所以,没有办法以标准的方式做到这一点。

但是有一种非标准的解决方法。 UISearchBar继承自UIView,您可以使用[searchBar subviews]访问它的子视图。 如果您在控制台中打印它的子视图,您将看到它有这些视图。

UISearchBarBackground,UISearchBarTextField。

因此,要更改字体大小,您只需要这样做

    UITextField *textField = [[searchBar subviews] objectAtIndex:1];
[textField setFont:[UIFont fontWithName:@"Helvetica" size:40]];

但是,如果UISearchBar在将来发生变化且文本字段不再位于位置1,则程序将崩溃,因此最好通过子视图检查UITextField的位置,然后设置字体大小。 / p>

答案 3 :(得分:13)

接受的答案不是UISearchBar应用字体的推荐方法。最好避免这种方法,并使用@rafalkitta或@josema提供的答案。

但要小心,这将通过应用程序应用于所有搜索栏。为了将此方法应用于特定搜索栏:创建UISearchBar的子类并在defaultTextAttributes上设置UITextField,如下所示

<强> Swift4

    let defaultTextAttribs = [NSAttributedStringKey.font.rawValue: UIFont.boldSystemFont(ofSize: 21.0), NSAttributedStringKey.foregroundColor.rawValue:UIColor.red]
    UITextField.appearance(whenContainedInInstancesOf: [CustomSearchBar.self]).defaultTextAttributes = defaultTextAttribs

<强>的OBJ-C(iOS11)

    UIFont *font = [UIFont boldSystemFontOfSize:21.0];
    UIColor *color = [UIColor redColor];
    NSDictionary * defaultTextAttribs = @{NSFontAttributeName:font, NSForegroundColorAttributeName: color};
    [UITextField appearanceWhenContainedInInstancesOfClasses:@[[CustomSearchBar class]]].defaultTextAttributes = defaultTextAttribs;

答案 4 :(得分:12)

您可以使用KVC(键值编码)获取文本字段

UITextField *textField = [self.searchBar valueForKey: @"_searchField"];
[textField setTextColor:[UIColor redColor]];
[textField setFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:17.0]];

答案 5 :(得分:11)

在swift 2.0中,以编程方式创建的搜索栏可以执行此操作:

override func layoutSubviews() {
  super.layoutSubviews()

  let textFieldInsideSearchBar = self.searchBar.valueForKey("searchField") as! UITextField
  textFieldInsideSearchBar.font = UIFont.systemFontOfSize(20)
 }

在这种情况下,我将代码放在UIView子类中,但它也可以在其他地方工作(即来自UIViewController的viewWillAppear)

答案 6 :(得分:8)

在swift 3中,您可以通过以下方式实现此目的:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).font = UIFont(name: "AvenirNextCondensed-Regular", size: 17.0)

答案 7 :(得分:5)

UITextField外观不适用于以编程方式创建的UISearchBar。您必须使用递归解决方法

- (void)viewDidLoad {
  [super viewDidLoad];
  [self recursivelySkinTextField:self.searchBar];
}

- (void)recursivelySkinTextField:(UIView *)view {
  if (!view.subviews.count) return;

  for (UIView *subview in view.subviews) {
    if ([subview isKindOfClass:[UITextField class]]) {
      UITextField *searchField = (UITextField *)subview;
      searchField.font = [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] font];
      searchField.textColor = [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] textColor];
    }
    [self recursivelySkinTextField:subview];
  }
}

答案 8 :(得分:3)

我想使用'Roboto-Regular'作为我项目中所有uisearchbars的默认字体。我做了一个uisearchbar扩展。

import UIKit
import CoreFoundation



class ViewController2 : UIViewController {


    override func viewDidLoad() {
        super.viewDidLoad();
    }

    @IBOutlet weak var slider: UISlider!
        @IBAction func slidervaluechanged(sender: UISlider) {
           print(Int(slider.value))

        }
}

用法:

extension UISearchBar {
func addRobotoFontToSearchBar(targetSearchBar:UISearchBar?) -> UISearchBar
{
    let textFieldInsideSearchBar = targetSearchBar!.valueForKey("searchField") as! UITextField
    textFieldInsideSearchBar.font = UIFont(name: "Roboto-Regular", size: 15.0)

//UIBarButtons font in searchbar
let uiBarButtonAttributes: NSDictionary = [NSFontAttributeName: UIFont(name: "Roboto-Regular", size: 15.0)!] 
UIBarButtonItem.appearance().setTitleTextAttributes(uiBarButtonAttributes as? [String : AnyObject], forState: UIControlState.Normal)

    return targetSearchBar!
}
}

答案 9 :(得分:3)

您不应该像其他答案一样使用私有API。如果要在整个应用程序中自定义搜索栏,可以使用类的外观代理。它允许修改搜索栏文本属性,占位符属性,取消按钮,文本字段背景图像,背景图像等。 使用示例:

if #available(iOS 9.0, *) {
    let searchBarTextAttributes = [
        NSFontAttributeName: UIFont.boldSystemFont(ofSize: 12), 
        NSForegroundColorAttributeName: UIColor.red
    ]
    // Default attributes for search text
    UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = searchBarTextAttributes

    // Attributed placeholder string
    UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: "Search...", attributes: searchBarTextAttributes)

    // Search bar cancel button
    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(searchBarTextAttributes, for: .normal)
    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "Cancel"
}

答案 10 :(得分:2)

在swift中重写了Eugene的递归解决方案 - 更改了函数名称以更准确地描述函数。对于我的情况,我需要更改字体大小。这对我有用。

func findAndSetTextField(view: UIView)
{
    if (view.subviews.count == 0)
    {
        return
    }

    for var i = 0; i < view.subviews.count; i++
    {
        var subview : UIView = view.subviews[i] as UIView
       if (subview.isKindOfClass(UITextField))
       {
            var searchField : UITextField = subview as UITextField
            searchField.font = UIFont(name: "Helvetica", size: 19.0)!
        }
        findAndSetTextField(subview)
    }
}

答案 11 :(得分:1)

完整的代码应该在下面:

for (UIView *v in (SYSTEM_VERSION_LESS_THAN(@"7.0")?searchBar.subviews:[[searchBar.subviews objectAtIndex:0] subviews])) {

    if([v isKindOfClass:[UITextField class]]) {
        UITextField *textField = (UITextField *)v;
        [textField setFont:fREGULAR(@"15.0")];

        return;
    }
}

答案 12 :(得分:1)

尝试按键找到搜索栏:

UITextField *searchField = [self.searchDisplayController.searchBar valueForKey:@"_searchField"];
searchField.font = [[UIFont fontWithName:@"Oswald" size:11];

答案 13 :(得分:1)

我知道这是一个旧线程,但是由于iOS 13 UISearchBar具有searchTextField属性,您可以在该属性上设置所需的字体。

答案 14 :(得分:1)

Swift 5.0

  searchBar.searchTextField.font = UIFont(name: "YOUR-FONT-NAME", size: 13)

答案 15 :(得分:1)

如果您需要方便的方法来更改所有应用程序搜索栏,请使用 Swift 5 中的一个简单子类:

class MySearchBar: UISearchBar {
    override func layoutSubviews() {
        super.layoutSubviews()

        if let textFieldInsideSearchBar = value(forKey: "searchField") as? UITextField {
            textFieldInsideSearchBar.font = UIFont(name: "Oswald-Light", size: 14)
        }
    }
}

答案 16 :(得分:0)

在您定义或设置UISearchBar的位置添加以下代码

Swift4:

UILabel.appearance(whenContainedInInstancesOf: [UISearchBar.self]).font = UIFont.init(name: "Ubuntu-Regular", size: 16)
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).font = UIFont.init(name: "Ubuntu-Regular", size: 16)

目标C:

[[UILabel appearanceWhenContainedIn:[UISearchBar class], nil] setFont:[UIFont fontWithName:@"Helvetica" size:12.0]];
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setFont:[UIFont fontWithName:@"Helvetica" size:12.0]];

答案 17 :(得分:0)

对于Swift 4.2 +

{{1}}

答案 18 :(得分:0)

iOS 13或更高版本:

> node-pty@0.9.0 install C:\Program Files\nodejs\node_modules\node-pty
> node scripts/install.js


C:\Users\HP\AppData\Roaming\nvm\v12.16.3\node_modules\node-pty>if not defined npm_config_node_gyp (node "C:\Users\HP\AppData\Roaming\nvm\v12.16.3\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "C:\Users\HP\AppData\Roaming\nvm\v12.16.3\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )
Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
  conpty.cc
  path_util.cc
  win_delay_load_hook.cc
C:\\Users\\HP\\AppData\\Local\\node-gyp\\Cache\\12.16.3\\x64\\node.lib : fatal error LNK1127: library is corrupt [C:\Users\HP\AppData\Roaming\nvm\v12.16.3\node_modules\node-pty\build\conpty.vcxproj]
  conpty_console_list.cc
  win_delay_load_hook.cc
C:\\Users\\HP\\AppData\\Local\\node-gyp\\Cache\\12.16.3\\x64\\node.lib : fatal error LNK1127: library is corrupt [C:\Users\HP\AppData\Roaming\nvm\v12.16.3\node_modules\node-pty\build\conpty_console_list.vcxproj]
  AgentLocation.cc
  winpty.cc
  BackgroundDesktop.cc
  Buffer.cc
  DebugClient.cc
  GenRandom.cc
  OwnedHandle.cc
  StringUtil.cc
  WindowsSecurity.cc
  WindowsVersion.cc
  WinptyAssert.cc
  WinptyException.cc
  WinptyVersion.cc
  win_delay_load_hook.cc
    Creating library C:\Users\HP\AppData\Roaming\nvm\v12.16.3\node_modules\node-pty\build\Release\winpty.lib and object C:\Users\HP\AppData\Roaming\nvm\v12.16.3\node_modules\node-pty\build\Release\winpty.exp
  winpty.vcxproj -> C:\Users\HP\AppData\Roaming\nvm\v12.16.3\node_modules\node-pty\build\Release\\winpty.dll
  Agent.cc
  AgentCreateDesktop.cc
  ConsoleFont.cc
  ConsoleInput.cc
  ConsoleInputReencoding.cc
  ConsoleLine.cc
  DebugShowInput.cc
  DefaultInputMap.cc
  EventLoop.cc
  InputMap.cc
  LargeConsoleRead.cc
  NamedPipe.cc
  Scraper.cc
  Terminal.cc
  Win32Console.cc
  Win32ConsoleBuffer.cc
  main.cc
  BackgroundDesktop.cc
  Buffer.cc
  DebugClient.cc
  GenRandom.cc
  OwnedHandle.cc
  StringUtil.cc
  WindowsSecurity.cc
  WindowsVersion.cc
  WinptyAssert.cc
  WinptyException.cc
  WinptyVersion.cc
  win_delay_load_hook.cc
  winpty-agent.vcxproj -> C:\Users\HP\AppData\Roaming\nvm\v12.16.3\node_modules\node-pty\build\Release\\winpty-agent.exe
gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\MSBuild.exe` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Users\HP\AppData\Roaming\nvm\v12.16.3\node_modules\npm\node_modules\node-gyp\lib\build.js:194:23)
gyp ERR! stack     at ChildProcess.emit (events.js:310:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
gyp ERR! System Windows_NT 10.0.18363
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\HP\\AppData\\Roaming\\nvm\\v12.16.3\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\HP\AppData\Roaming\nvm\v12.16.3\node_modules\node-pty
gyp ERR! node -v v12.16.3
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-pty@0.9.0 install: `node scripts/install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-pty@0.9.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\HP\AppData\Roaming\npm-cache\_logs\2020-05-29T09_24_34_336Z-debug.log