TabBar 项目图像到宽

TabBar Item Image to Wide

我像这样使用用户个人图片作为 TabBar 项目:

func setUpProfileImage(){
    let userID = Auth.auth().currentUser!.uid

    let ref2 = Database.database().reference().child("users").child(userID)
     ref2.child("profileImageUrl").observeSingleEvent(of: .value, with: { snapshot in
         if let url = snapshot.value as? String {
             URLSession.shared.dataTask(with: URL(string: url)!) { data, response, error in
                 if error == nil {
                     let image = UIImage(data: data!)
                     

                     DispatchQueue.main.async {
                     if let lastTabBarButton = self.tabBar.subviews.last, let tabItemImageView = lastTabBarButton.subviews.first {
                         if let accountTabBarItem = self.tabBar.items?.last {
                             accountTabBarItem.selectedImage = nil
                             accountTabBarItem.image = nil
                         }
                         let imgView = UIImageView()
                         imgView.frame = tabItemImageView.frame
                         imgView.layer.cornerRadius = tabItemImageView.frame.height/2
                         imgView.layer.masksToBounds = true
                         imgView.contentMode = .scaleAspectFill
                         imgView.clipsToBounds = true
                         imgView.image = image
                         self.tabBar.subviews.last?.addSubview(imgView)
                     }
                 }
                }
             }.resume()
         }
     })
}

图像显示出来了,但是太宽了 - 有没有办法使宽度与高度相同?

您设置的框架需要调整,尝试这样设置框架:

let imgView = UIImageView()
let frame = tabItemImageView.frame
imgView.frame = CGRect(
    x: frame.origin.x + (frame.width / 2) - (frame.height / 2),
    y: frame.origin.y,
    width: frame.height,
    height: frame.height
)