簡體   English   中英

UIButton大小錯誤的圖像和標題插入

[英]UIButton sizing wrong with image and title inset

它似乎不像UIButton instrinsicSize和/或sizeToFit考慮到標題左邊緣插入,或者某些東西搞砸了我的期望。

為了演示,我在視圖中有兩個自定義類型按鈕,標題都是“按鈕”。 我想在標題左側的按鈕中添加圖像。

    var image = UIImage(named: "circledPlay")
    image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)

    self.button1.setImage(image, forState: UIControlState.Normal)
    self.button1.invalidateIntrinsicContentSize()
    self.button1.sizeToFit()

    self.button2.setImage(image, forState: UIControlState.Normal)
    self.button2.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0)
    self.button2.invalidateIntrinsicContentSize()
    self.button2.sizeToFit()

結果如下:

屏幕截圖

請注意第二個按鈕被截斷。

所以我的問題是,如果有人之前已經看過這個(並希望有一個解決方案)或者我感到困惑,這表現得如預期的那樣(並且希望知道正確的方法)?

正如文檔中所述,對於titleEdgeInsets :“該按鈕不使用此屬性來確定intrinsicContentSizesizeThatFits: ”。 因此,設置titleEdgeInsets只會移動標題標簽,但不會影響按鈕的大小。 如果您希望按鈕在內容周圍有更多填充,請同時設置contentEdgeInsets。 我認為你不需要調用sizeToFitinvalidateIntrinsicContentSize (但我不確定)。

您可以使用contentEdgeInsetstitleEdgeInsets來實現它。

button2.setImage(image, for: .normal)
button2.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
button2.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 10)
button2.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, -10)
button2.setTitle("Button", for: .normal)
button2.sizeToFit()

按鈕結果

暫無
暫無

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

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