iOS - 使用约束将图像和文本添加到titleview

时间:2018-04-23 09:15:48

标签: ios swift

我正在尝试为我的导航栏创建一个自定义标题视图,旁边有一些文字,这就是我感谢https://stackoverflow.com/a/47404105的方式:

class CustomTitleView: UIView
{

var title_label = CustomLabel()
var left_imageView = UIImageView()

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

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

func setup(){
    self.addSubview(title_label)
    self.addSubview(left_imageView)

}

func loadWith(title: String, leftImage: UIImage?)
{
    title_label.text = title
    title_label.font = UIFont.systemFont(ofSize: FontManager.fontSize + 5)
    left_imageView.image = leftImage

    setupFrames()
}

func setupFrames()
{

    let height: CGFloat = 44
    let image_size: CGFloat = height * 0.8

    left_imageView.frame = CGRect(x: 0,
                                  y: (height - image_size) / 2,
                                  width: (left_imageView.image == nil) ? 0 : image_size,
                                  height: image_size)

    let titleWidth: CGFloat = title_label.intrinsicContentSize.width + 10
    title_label.frame = CGRect(x: left_imageView.frame.maxX + 5,
                               y: 0,
                               width: titleWidth,
                               height: height)



    contentWidth = Int(left_imageView.frame.width)
    self.frame = CGRect(x: 0, y: 0, width: CGFloat(contentWidth), height: height)
}


var contentWidth: Int = 0 
override func layoutSubviews() {
    super.layoutSubviews()

    self.frame.size.width = CGFloat(contentWidth)

}

但问题是我不想对框架进行硬编码,我想使用约束但我不知道从哪里开始。

1 个答案:

答案 0 :(得分:0)

首先取一个imageView并根据您的要求设置约束,然后除了Label设置它的约束外,再取一个imageView。在您要显示它们的navigationBar中执行此操作。