【问题标题】:Automatic height for XIB and container viewsXIB 和容器视图的自动高度
【发布时间】:2016-10-06 13:04:30
【问题描述】:

我正在尝试为我的故事板构建可重复使用的视图,让我们从 XIB 开始:

此视图包含一个带有标签的 UITextField 以显示错误,文件的所有者连接到此类:

import Foundation
import UIKit

@IBDesignable
class TextField: UIView {

    @IBOutlet weak var textField: UITextField!

    @IBOutlet weak var errorLabel: UILabel!

    @IBOutlet weak var errorLine: UIImageView!

    var view: UIView!

    func loadViewFromNib() -> UIView {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: "TextField", bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView

        return view
    }

    func xibSetup() {
        view = loadViewFromNib()
        view.frame = bounds
        view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
        addSubview(view)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        xibSetup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        xibSetup()
    }

    @IBInspectable var placeholder: String? {
        didSet {
            textField.placeholder = placeholder
        }
    }

    @IBInspectable var isSecureTextEntry: Bool = false {
        didSet {
            textField.isSecureTextEntry = isSecureTextEntry
        }
    }

    @IBInspectable var errorText: String? {
        didSet {
            errorLabel.text = errorText
        }
    }

    func showError() {
        errorLine.isHidden = false
        errorLabel.isHidden = false
    }

    func hideError() {
        errorLine.isHidden = true
        errorLabel.isHidden = true
    }
}

然后我在 Main.storyboard 上使用它作为 UIView,将类设置为 TextField:

这里的问题是,每次我使用这个 TextField 类时,我都需要为高度添加一个约束,我尝试使用固有大小作为 Main.storyboard 上 UIView 的占位符(删除高度约束)但在运行时与 XIB 的高度不同。

同样的问题也发生在视图控制器的容器视图上,我有这种情况:

如何使容器视图与嵌入的视图控制器高度相同? (作为测试,我将大红色视图控制器的高度设置为 1500px 以查看它是否滚动,如果我对容器视图的高度进行约束,则滚动视图的内容大小是正确的,但我想避免限制高度,我希望它是自动的)

提前感谢您的帮助

【问题讨论】:

  • FWIW,我尝试做同样的事情,但很痛苦。我最终在代码中布置了我的单元格子视图,然后只通过约束指定高度。我还需要子视图来控制容器的高度,并且找不到比设置通信线路更好的方法来与父视图通信并通过 NSLayoutConstraint 手动更改它。不理想,但肯定不是一个糟糕的解决方案。

标签: ios swift autolayout interface-builder xcode8


【解决方案1】:

我使用了我在此处描述的相同技术: https://medium.com/zenchef-tech-and-product/how-to-visualize-reusable-xibs-in-storyboards-using-ibdesignable-c0488c7f525d#.3c0javomy

确保 Xib 中的所有约束都定义了视图的高度。 当您在情节提要中使用它时,您不需要再次设置高度。但是,在渲染视图之前,您会在情节提要中看到 IB 约束错误。

【讨论】:

    猜你喜欢
    • 2015-03-07
    • 2016-12-29
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多