以下僅僅是對代表團的測試。我做的是,1)畫一個矩形,2)用代表設置這個矩形的線寬,3)希望故事板可以更新它的顯示。斯威夫特代表團和故事板@IBDesignable問題
有兩個問題:
第一是:如果我使用「testView.widthdelegate = ViewController()
」而不是「testView.widthdelegate = self
」中,「var widthValue: CGFloat? = widthdelegate?.trueWidth
」將是零,但它應該是50,什麼是「自我」之間的不同, 「ViewController()
」?
第二個是:我還想更新故事板中的繪製結果,在那裏你可以看到我做了SetNeedDisplay()
但根本沒用,我怎麼能這樣做?
查看
import UIKit
protocol widthDelegate: class {
var trueWidth: CGFloat { get }
}
@IBDesignable
class TestView: UIView {
weak var widthdelegate: widthDelegate?
override func drawRect(rect: CGRect) {
var widthValue: CGFloat? = widthdelegate?.trueWidth ?? 1.0
rectangle(widthRefer: widthValue!)
println("width in TestView is \(widthdelegate?.trueWidth)")
}
func rectangle(#widthRefer: CGFloat) -> UIBezierPath{
var rect = UIBezierPath(rect: CGRect(x: bounds.width/2-50, y: bounds.height/2-50, width: 100, height: 100))
rect.lineWidth = widthRefer
rect.stroke()
return rect
}
}
控制器
import UIKit
class ViewController: UIViewController,widthDelegate {
var trueWidth: CGFloat = 50
@IBOutlet var testView: TestView!{
didSet{ //after the storyboard loaded.
// testView.widthdelegate = ViewController()
testView.widthdelegate = self
testView.setNeedsDisplay()
}
}
}
嘿哥們,非常感謝:) –