簡體   English   中英

使用SVG圖像時,如何設置作為UIBarButtonItem的自定義視圖添加的UIButton的寬度和高度?

[英]How to set width and heigh of UIButton that is added as custom view of UIBarButtonItem when using SVG images?

我有一個矢量圖像,從phosphor-icons下載:

我下載了.svg版本的圖標。 當您在圖像編輯器中打開此矢量文件時,您會看到它的尺寸為192x192 我猜這與矢量文件無關,但是......

我有這段代碼:

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 32, height: 32))

button.imageView?.contentMode  = .scaleAspectFit
button.backgroundColor = .yellow
button.setImage(UIImage(named: "alien"), for: .normal)
button.setTitle(nil, for: .normal)
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
let item = UIBarButtonItem(customView: button)

navigationItem.setRightBarButtonItems([item], animated: true)

現在的問題是,如果我使用這個原始svg圖像 (192x192),按鈕會縮小,看起來像這樣:

大外星人

但我不希望此按鈕具有這些尺寸,而是那些設置為:

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 32, height: 32))

現在,如果我 go 到一個圖像編輯器,並將這個矢量文件的大小更改為22x22 (它仍然是svg文件),它顯示如下:

外星人正常

這看起來像我想要的。

問題是,我認為 Xcode 會根據設備的像素密度從這個svg生成所需的png文件。 因此,在這種情況下,比方說,在使用@3x圖像的較新設備上,在編譯時,由於我的按鈕被定義為32x32點,將創建一個96px X 96px圖像並將其用作@3x圖像。

此外,我認為這將像描述的那樣工作,無論物理的“尺寸”是什么。 svg文件是,因為它是一個矢量,它應該根據視圖指示進行放大/縮小。 我哪里錯了,以及如何使這個按鈕看起來與第二張圖片相同,無論實際情況如何。 svg尺寸?

編輯:

在 Attributes Inspector 中,對於這個資產,我設置了Preserve Vector Data並選擇了Single Scale選項。

添加按鈕作為條形按鈕項的customView時,UIKit 將自動使用自動布局。

所以,你的UIButton(frame: CGRect(x: 0, y: 0, width: 32, height: 32))沒有任何效果。

我從您鏈接到的網站上抓取了“alien.svg”,並使用這些未編輯的設置:

在此處輸入圖像描述

然后,使用此代碼(在viewDidLoad()中):

    let button = UIButton()
    
    button.backgroundColor = .yellow
    button.setImage(UIImage(named: "alien"), for: .normal)
    button.setTitle(nil, for: .normal)

    // adding the button as a custom bar button item view
    //  automatically uses auto-layout
    button.widthAnchor.constraint(equalToConstant: 32).isActive = true
    button.heightAnchor.constraint(equalTo: button.widthAnchor).isActive = true
    
    button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)

    let item = UIBarButtonItem(customView: button)

    // you can use either
    //navigationItem.rightBarButtonItem = item
    
    // or
    navigationItem.setRightBarButtonItems([item], animated: true)

我們得到這個結果:

在此處輸入圖像描述

另一種在不使用自動布局約束的情況下實現此目的的方法,就像您評論的那樣,是為自定義customview使用UIView()

   let view = UIView(frame: button.frame)
   view.addSubview(button)

   let item = UIBarButtonItem(customView: view)
   self.navigationItem.setRightBarButtonItems([item], animated: true)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM