2016-12-14 105 views
0

我想添加一個「日曆天」的形象環繞,像這樣的一個可點擊的UI按鈕一些文字:調整大小的背景圖像上的UIButton

let button = UIButton() 
let X_Offset : CGFloat = (95 * CGFloat(buttonCount)) + 10 
let scrollHeight = scrollView.bounds.height 

button.frame = CGRect(x: X_Offset, y: scrollHeight/6, width: 70, height: 60) 
let buttonText = event.startTime.toShortDayOfWeekString() + "\n" + event.startTime.toShortDayOfMonthString() 
button.titleLabel!.lineBreakMode = .byWordWrapping 
button.titleLabel!.textAlignment = .center 
button.setTitle(buttonText, for: .normal) 
button.tag = i 

button.backgroundColor = CompanyColor.Red.color 
let image = UIImage(named: "calendarDay") 
button.setBackgroundImage(image, for: .normal) 
button.titleLabel?.font = UIFont(name: "Roboto", size: 14) 
button.layer.cornerRadius = 8 
button.clipsToBounds = true 

,但圖像侵佔文字有點太很多: encroaching image in uibutton 如何獲得背景圖片以略微放大併爲文字留出足夠的空白?

回答

0

我想你正在尋找什麼是imageEdgeInsetsUIButton。設置這些屬性可讓您移動圖像,除了其默認位置。你必須四處遊玩才能得到你想要的結果。

有兩種方法可以做到這一點。一個使用Interface Builder,另一個使用編程方式。接口生成器是我猜的最簡單的方法。下圖顯示瞭如何設置UIButton的這些屬性。

Edit these properties to get your desired result

,或者嘗試使用編程這樣

button.imageEdgeInsets = UIEdgeInsets(top: -10, left: 32, bottom: -10, right: 50) 

您可以將標題這樣

button.titleEdgeInsets = UIEdgeInsets(top: 0, left:0, bottom: 0, right: 20) 

注:設置UIEdgeInsets這樣可能會有不同的結果,如果你有動態大小按鈕,例如針對不同的屏幕尺寸。始終確保它看起來像所有屏幕尺寸一樣。

+0

嗨Jay,這些似乎對背景圖像沒有任何影響,只是前景之一。 –

+0

好吧!一種你可以移動背景圖像的方法是通過子類「UIButton」,你必須重寫'func backgroundRect(forBounds bounds:CGRect)'。我很確定這會適用於你正在尋找的東西。 – Jay