2017-07-14 90 views
1

我在應用程序的頁面上添加了一個簡單的更新按鈕。該按鈕有一個imageView,並且應該在視圖頂部有一個標題「立即更新」。Swift 3.0 - UIButton標籤高度爲零高度

在視圖層次結構中,我可以看到UILabel作爲UIButton的子視圖。但打印的UILabel的描述返回框架

(250 20; 283 0). 

這是我的代碼

let updateButton = UIButton() 
updateButton.frame = CGRect(x: centreX(parent: self.view, width: 150), y: 200, width: 150, height: 40) 
updateButton.setImage(UIImage(named:"my-image"), for: .normal) 

updateButton.setTitle("Update Now", for: .normal) 
updateButton.titleLabel?.sizeToFit() 
updateButton.titleLabel?.frame = updateButton.frame 
updateButton.setTitleColor(UIColor.black, for: .normal) 
self.view.addSubview(updateButton) 

我想無論是線

updateButton.titleLabel?.sizeToFit() 
updateButton.titleLabel?.frame = updateButton.frame 

會改變標籤的框架的高度。有什麼我在這裏失蹤?

使用雨燕3.0和iOS 10

回答

1

我發現了問題。來自UIButton文檔

提供標題字符串或圖像;爲您的內容適當調整按鈕大小。

這意味着只能設置其中的一個屬性。當我首先設置圖像時,這就是展示的內容。這是我看不到標籤的原因。

正如我解決我有2個解決方案:

首先 - 使用的標題和設置背景顏色

updateButton.setTitle("Update Now", for: .normal) 
updateButton.setTitleColor(UIColor.white, for: .normal) 
updateButton.backgroundColor = UIColor(patternImage: UIImage(named: "my-image")!) 

這是我用過的東西。我不得不縮放背景圖片以適應視圖。

或者 - 創建一個新的圖像組合立即更新文本

updateButton.setImage(UIImage(named:"my-new-image"), for: .normal) 

我希望這可以幫助別人。

2

我認爲你需要設置背景圖片,而不是像類似如下

updateButton.setBackgroundImage(UIImage(named: "my-image"), for: .normal) 
+1

是的你說得對,謝謝。這是我的一個錯誤,當複製代碼並改變它去除我的圖像實際名稱時。 – ochhii