如何在Swift中使用一个位置导航栏项目?

问题描述 投票:0回答:1

我有一个导航栏,目前只有一个后退按钮。我试图在导航栏的右侧添加一个图像按钮,但是我使用的图像大于导航栏,最终覆盖了后退按钮,并且位置异常。

这是代码:

let mapBtn = UIButton(type: .system)
mapBtn.setImage(#imageLiteral(resourceName: "map-1"), for: .normal)
mapBtn.frame = CGRect(x: 0,y: 0,width: 5,height: 5)

self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: mapBtn)

这是正在发生的情况的图像:https://imgur.com/a/kzcwbGK

反正有没有向mapBtn添加约束以使其依原样粘在右侧?

swift uikit navigationbar
1个回答
0
投票

尝试调整图像大小

   func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage? {
    let size = image.size

    let widthRatio  = targetSize.width  / image.size.width
    let heightRatio = targetSize.height / image.size.height

    // Figure out what our orientation is, and use that to form the rectangle
    var newSize: CGSize
    if(widthRatio > heightRatio) {
        newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
    } else {
        newSize = CGSize(width: size.width * widthRatio,  height: size.height * widthRatio)
    }

    // This is the rect that we've calculated out and this is what is actually used below
    let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

    // Actually do the resizing to the rect using the ImageContext stuff
    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    image.draw(in: rect)
    if let newImage = UIGraphicsGetImageFromCurrentImageContext(){
        UIGraphicsEndImageContext()

        return newImage

    }else{
        return nil
    }
}
 let mapBtn = UIButton(type: .system)
 let img = UIImage(named: "map-1")
 let resizedImage = resizeImage(image: img, targetSize:  CGSize(width: 5.0, height: 5.0) 
 mapBtn.frame = CGRect(x: 0,y: 0,width: 5,height: 5)
 mapBtn.setImage(resizedImage, for: .normal)
 self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: mapBtn)

0
投票

设置此

 mapBtn.imageView?.contentMode = .scaleAspectFit
© www.soinside.com 2019 - 2024. All rights reserved.