[英]Swift UIButton Subclass not Showing on device or Simulator
我有以下代碼,並聲明了IBDesignable。
DrawRect在Interface Builder中顯示得很好,但在Simulator或Device上卻完全沒有。
有人知道為什么嗎?
import UIKit
import QuartzCore
@IBDesignable class VideoButton: UIButton {
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect)
{
let color2 = UIColor(red: 0.500, green: 0.500, blue: 0.500, alpha: 0.000)
//// Oval Drawing
var ovalPath = UIBezierPath(ovalInRect: CGRectMake(frame.minX + floor(frame.width * 0.03571) + 0.5, frame.minY + floor(frame.height * 0.03571) + 0.5, floor(frame.width * 0.96429) - floor(frame.width * 0.03571), floor(frame.height * 0.96429) - floor(frame.height * 0.03571)))
color2.setFill()
ovalPath.fill()
UIColor.whiteColor().setStroke()
ovalPath.lineWidth = 3
ovalPath.stroke()
//// Rectangle Drawing
let rectanglePath = UIBezierPath(roundedRect: CGRectMake(frame.minX + floor(frame.width * 0.25714 + 0.5), frame.minY + floor(frame.height * 0.34286 + 0.5), floor(frame.width * 0.60000 + 0.5) - floor(frame.width * 0.25714 + 0.5), floor(frame.height * 0.64286 + 0.5) - floor(frame.height * 0.34286 + 0.5)), cornerRadius: 2)
color2.setFill()
rectanglePath.fill()
UIColor.whiteColor().setStroke()
rectanglePath.lineWidth = 3
rectanglePath.stroke()
//// Bezier Drawing
var bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(frame.minX + 0.61429 * frame.width, frame.minY + 0.50536 * frame.height))
bezierPath.addLineToPoint(CGPointMake(frame.minX + 0.75714 * frame.width, frame.minY + 0.34286 * frame.height))
bezierPath.addLineToPoint(CGPointMake(frame.minX + 0.75714 * frame.width, frame.minY + 0.64286 * frame.height))
bezierPath.addLineToPoint(CGPointMake(frame.minX + 0.61429 * frame.width, frame.minY + 0.50536 * frame.height))
bezierPath.closePath()
bezierPath.lineJoinStyle = kCGLineJoinRound;
color2.setFill()
bezierPath.fill()
UIColor.whiteColor().setStroke()
bezierPath.lineWidth = 3
bezierPath.stroke()
// }
}
}
將對“框架”的引用更改為“矩形”,它應該插入設備和模擬器中。
您不應該為UIButton子類重寫drawRect:
:。 沒有必要; 您可以使用其各種屬性和方法來自定義UIButton的外觀。 目前尚不清楚為什么要這樣做。 (您正在執行而不是調用super
的事實可能解釋了這個問題;但解決方案不是,請調用super
,但首先不要這樣做。)
我最近一直在嘗試做類似的事情-創建UIButton的子類,重寫drawRect()
以便繪制一個簡單的自定義圖標(我正在制作一個在每個“播放”和“停止”之間切換的播放/停止按鈕點擊):
也許我對iOS開發的了解還不夠,但是由於網上有人回答其他問題和不鼓勵擴展UIButton
類的老帖子 ,我不明白為什么這不是一個好主意。 當然,您可以通過設置自定義背景圖片來自定義按鈕,但是我認為這不像覆蓋drawRect
那樣靈活(更不用說drawRect
想要更改某些內容時都很難編輯按鈕,因為您必須進行編輯而不是幾行代碼)。
我確信還有其他方法可以達到相同的結果(例如,通過自定義的UIView
監聽觸摸事件來實現按鈕),但是我認為最干凈,最簡單的方法仍然只是擴展UIButton
類。 畢竟,它本身是UIView
的子類。
關於您的代碼-盡管我必須稍微更改顏色以使其在白色背景下顯示(即UIColor.blackColor().setStroke()
而不是UIColor.whiteColor().setStroke()
,但它在我的環境中似乎可以正常工作UIColor.whiteColor().setStroke()
)。 另外,正如@Astrodan所提到的,使用rect
而不是frame
可能是一個好主意,因為它已傳遞給您(盡管代碼對我而言適用於frame
):
XCode中的實時渲染情節提要:
在iPhone 6模擬器上:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.