如何在 UINavigationBar sizeToFit 中设置 UITextField?
How to set UITextField in UINavigationBar sizeToFit?
我一直找不到解决这个问题的方法。当放置在 UINavigationBar 中时,我无法给 UITextField,textField
,sizeToFit
属性。
我试过了:textField.sizeToFit()
当然,Interface Builder 在放入 UINavigationBar 时不会提供任何选项。任何解决方案都会很棒,谢谢!
为您的 textField
创建一个出口,然后在 viewDidLoad
中调用此函数(您也可以将下面的代码直接粘贴到 viewDidLoad
中):
func setWidth() {
var frame: CGRect = self.textField.frame
frame.size.width = self.view.frame.width
self.textField.frame = frame
}
结果:
iPhone 6S Plus:
iPhone 6:
iPhone 5:
更新
要更改旋转大小,请添加以下代码行:
在viewDidLoad
中添加这个观察者:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "rotated", name: UIDeviceOrientationDidChangeNotification, object: nil)
添加这个函数来检测方向然后调整 textField
:
func rotated(){
if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)){
print("landscape")
setWidth()
}
if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)){
print("Portrait")
setWidth()
}
}
我一直找不到解决这个问题的方法。当放置在 UINavigationBar 中时,我无法给 UITextField,textField
,sizeToFit
属性。
我试过了:textField.sizeToFit()
当然,Interface Builder 在放入 UINavigationBar 时不会提供任何选项。任何解决方案都会很棒,谢谢!
为您的 textField
创建一个出口,然后在 viewDidLoad
中调用此函数(您也可以将下面的代码直接粘贴到 viewDidLoad
中):
func setWidth() {
var frame: CGRect = self.textField.frame
frame.size.width = self.view.frame.width
self.textField.frame = frame
}
结果:
iPhone 6S Plus:
iPhone 6:
iPhone 5:
更新
要更改旋转大小,请添加以下代码行:
在viewDidLoad
中添加这个观察者:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "rotated", name: UIDeviceOrientationDidChangeNotification, object: nil)
添加这个函数来检测方向然后调整 textField
:
func rotated(){
if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)){
print("landscape")
setWidth()
}
if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)){
print("Portrait")
setWidth()
}
}