将属性标签设置为导航标题 [英] Setting attributed label as navigation title

查看:36
本文介绍了将属性标签设置为导航标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 swift 4 开发 IOS.我必须制作导航控制器,中间对齐的应用程序标题与左侧的图像.但我不知道如何将图像附加到其左侧.属性图像总是在它的右边.

I am working on IOS using swift 4. I have to make the Navigation controller, with the center Aligned App title with Image at its left. But I am not getting how to attach image to its left. The attributed Image always goes to its right.

为此,我将字符串附加两次.下面是代码

For this I am appending the string twice. below is the code

   //Get image and set it's size
    let image = UIImage(named: "user2")
    let newSize = CGSize(width: 30, height: 30)

    //Resize image
    UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
    image?.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
    let imageResized = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    //Create attachment text with image
    let attachment = NSTextAttachment()
    attachment.image = imageResized
    let attachmentString = NSAttributedString(attachment: attachment)
    let myString = NSMutableAttributedString(string: "")
    myString.append(attachmentString)
    let strAttachment = NSAttributedString(string: "My Ios App" )
    myString.append(strAttachment)

    navLabel.attributedText = myString

    self.navigationItem.titleView = navLabel

我得到的是像左下图这样的东西

What I am getting is some thing like below image is on left

我想要的:

我只想显示图像,文本和图像之间有空格.我希望图像看起来很好很漂亮.文本应垂直于图像居中.实现这一目标的好方法是什么?

I just want the image to be shown with the space between text and Image. I want the image to be look good and nice. Text should be center vertically to the image. what is good way of achieving this ?.

推荐答案

使用此代码,您将获得输出:

        let navgationView = UIView()

        let label = UILabel()
        label.text = " My Ios App"
        label.sizeToFit()
        label.center = navgationView.center
        label.textAlignment = NSTextAlignment.center

        let image = UIImageView()
        image.image = UIImage(named: "user")
        let imageAspect = image.image!.size.width/image.image!.size.height
        image.frame = CGRect(x: label.frame.origin.x-label.frame.size.height*imageAspect, y: label.frame.origin.y, width: label.frame.size.height*imageAspect, height: label.frame.size.height)
        image.contentMode = UIViewContentMode.scaleAspectFit

        navgationView.addSubview(label)
        navgationView.addSubview(image)

        self.navigationItem.titleView = navgationView
        navgationView.sizeToFit()

输出:-

希望它有帮助.!!

这篇关于将属性标签设置为导航标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆