ios - 如何在 UINavigationBar sizeToFit 中设置 UITextField?

标签 ios swift uinavigationcontroller uitextfield uinavigationbar

我一直找不到解决这个问题的方法。当放置在 UINavigationBar 中时,我无法为 UITextField、textField 提供 sizeToFit 属性。

我试过:textField.sizeToFit()

当然,Interface Builder 在放入 UINavigationBar 时不会提供任何选项。任何解决方案都会很棒,谢谢!

最佳答案

为您的 textField 创建一个 outlet,然后在 viewDidLoad 中调用此函数(您也可以将下面的代码直接粘贴到 viewDidLoad 中) :

func setWidth() {
    var frame: CGRect = self.textField.frame
    frame.size.width = self.view.frame.width
    self.textField.frame = frame
}

结果:

iPhone 6S Plus: enter image description here

iPhone 6: enter image description here

iPhone 5: enter image description here

更新
要更改旋转大小,请添加以下代码行:

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()
    }
}

关于ios - 如何在 UINavigationBar sizeToFit 中设置 UITextField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34832465/

相关文章:

ios - App Transport Security 已阻止解析文件... Swift 2 错误

ios - viewDidAppear 在 iOS5 中调用了两次

ios - 添加目标 :action:forControlEvents: unrecognized selector sent to instance - uibutton in uitablecell

ios - 使用 CAShapeLayer 对蒙版部分的透明度进行动画处理

ios - Swift 中共享 watchOS/iOS 类的平台特定代码?

ios - 将 UIImagePickerController 的外观设置回默认值

iOS:包裹在导航 Controller 中时将数据传递给模态 VC

ios TableView不同的单元格高度

ipad - 获取iPad屏幕键盘旋转后的大小

ios - subview 调整大小至全屏