如何制作更圆润的UITextField?就像iPad上Safari中的搜索栏一样。

9

你好,我想让一个UITextField看起来像iPad上Safari应用程序中可用的Google搜索字段。该字段的目的将是相同的(搜索框)。

我知道我可以使用UISearchBar,但我必须使用hackish代码来摆脱放大镜图标和背景,我不想要那个。

我附上了一个图片,其中包含苹果公司用作其搜索框的TextField。如何修改UITextField以使其外观和行为与此截图中的搜索字段相同? alt text

我尝试修改UITextField的layer roundedCorners属性,但这并没有按预期工作。

非常感谢任何帮助!

谢谢!


当你在尝试使用roundedCorners时,你是否确保已经添加了quartzcore框架,并且在你的ViewController子类中导入了必要的头文件? - samsam
5个回答

17

您可以在任何UIView子类上设置Corner-Radius。

  1. 将QuartzCore.framework添加到您的项目中。
  2. 在您的UIViewController子类中添加#import <QuartzCore/QuartzCore.h>(您需要访问所选择的UITextfield实例的地方)。
  3. 在viewDidLoad / viewWillAppear(或任何其他已经实例化了UITextfield的地方)中调用[yourTextField.layer setCornerRadius:14.0f];
  4. 尝试不同的cornerRadius值,直到达到理想效果。

虽然这是一个获得圆角的好方法,但你无法获得他展示的完全相同的外观和感觉,特别是阴影。 - Jerry Jones

10

使用以下代码。这对我有效:

searchField= [[UITextField alloc] initWithFrame:CGRectMake(0,0,150,31)];
searchField.delegate = self;
searchField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
searchField.textColor = [UIColor colorWithRed:102.0/255 green:102.0/255 blue:102.0/255 alpha:1.0];
searchField.textAlignment = UITextAlignmentLeft;
searchField.font = [UIFont fontWithName:@"Helvetica" size:15];
searchField.autocorrectionType = UITextAutocorrectionTypeNo;
searchField.contentVerticalAlignment =UIControlContentVerticalAlignmentCenter;
searchField.clearsOnBeginEditing = NO;
searchField.autocapitalizationType = UITextAutocapitalizationTypeNone;
searchField.autocorrectionType = UITextAutocorrectionTypeNo;
searchField.keyboardType = UIKeyboardTypeURL;
searchField.returnKeyType = UIReturnKeySearch;        
searchField.clearButtonMode = UITextFieldViewModeWhileEditing;
searchField.rightViewMode = UITextFieldViewModeUnlessEditing;
searchField.layer.cornerRadius = 17;
searchField.placeholder=@"Google Search";
searchField.borderStyle = UITextBorderStyleRoundedRect;//To change borders to rounded
searchField.layer.borderWidth = 1.0f; //To hide the square corners 
searchField.layer.borderColor = [[UIColor grayColor] CGColor]; //assigning the default border color
UIBarButtonItem *searchFieldItem = [[UIBarButtonItem alloc] initWithCustomView:searchField];

3

将UITextField的背景属性设置为适当的图像,例如这个: alt text


在这种情况下,如果对齐设置为右侧或左侧,文本将会太靠近边缘。 - Shmidt

0

为什么不尝试一下用输入字段的单独图像,并将其放置在真实的textField控件下面的技巧呢?但是,您需要操纵所放置的textField的颜色,以使其透明。


-4
使用一个带有所需圆角的图形,然后将一个文本视图放在其上方。

谢谢您的回复,但我认为苹果在构建该功能时没有使用类似的东西。 - Horatiu Paraschiv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接