我目前正在我的应用程序中实现某种浏览器。但是,我是 iOS 编程的新手,因此不知道如何以编程方式更改文本字段的宽度。当前实现中发生的是文本字段越过导航 Controller 的后退按钮。因此,我需要文本字段在左侧留出一些空间。
有人知道怎么做吗?这可能吗?
/* Create the page title label */
UINavigationBar *navBar = self.navigationController.navigationBar;
CGRect labelFrame = CGRectMake(kMargin, kSpacer,
navBar.bounds.size.width - 2*kMargin, kLabelHeight);
UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont systemFontOfSize:12];
label.textAlignment = NSTextAlignmentCenter;
[navBar addSubview:label];
self.pageTitle = label;
/* Create the address bar */
CGRect addressFrame = CGRectMake(kMargin, kSpacer*2.0 + kLabelHeight,
labelFrame.size.width, kAddressHeight);
UITextField *address = [[UITextField alloc] initWithFrame:addressFrame];
address.autoresizingMask = UIViewAutoresizingFlexibleWidth;
address.borderStyle = UITextBorderStyleRoundedRect;
address.font = [UIFont systemFontOfSize:17];
address.keyboardType = UIKeyboardTypeURL;
address.autocapitalizationType =UITextAutocapitalizationTypeNone;
address.autocorrectionType = UITextAutocorrectionTypeNo;
address.clearButtonMode = UITextFieldViewModeWhileEditing;
[address addTarget:self
action:@selector(loadRequestFromAddressField:)
forControlEvents:UIControlEventEditingDidEndOnExit];
[navBar addSubview:address];
self.addressField = address;
最佳答案
您可以控制 UI 元素的定位和大小,在本例中是您的 UITextField
通过修改其 frame
属性(property)。
frame
是 CGRect
类型的矩形.它由四个组件组成,这些组件指定其在屏幕坐标空间内的定位和大小。
前两个组件是:x
和 y
.这些代表矩形的位置。屏幕左上角是点(0,0),所以你的自定义x
和 y
值是相对于这一点的。
在您的情况下,您需要修改 x
View 的属性,正如您所描述的那样,您的 UITextField
太靠左了。增加 x
文本字段框架的值会将文本字段向右移动。
你可以这样做,例如通过在您的 UITextField
之后调用执行以下操作已初始化(假设其变量名为 address
):
address.frame = CGRectMake(address.frame.origin.x + 10.0, address.frame.origin.y, address.frame.size.width, address.frame.size.width)
这会将您的文本字段向右移动 10 磅。
关于ios - 更改 UITextField 宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26368800/