我剛剛在一週前在iOS上開始了我的第一個應用程序。我創建了一個自定義視圖,使用AppleDeveloperWebsite自定義評級控制教程在我的應用程序中使用它。在iOS中的自定義視圖大小不是動態的
現在我已經選擇了故事板中的iPhone7設備,並且我在iPhone 7仿真器上運行了它,但它在iPhone 5仿真器上運行時(屏幕大小發生了變化),我的自定義視圖超出了屏幕。我的所有其他控件大小調整大小,因爲我設置約束,但只有我的自定義視圖大小搞砸了。
請幫助
import UIKit
@IBDesignable class xRadioButtonView: UIView {
var button: UIButton!
var label: UILabel!
@IBInspectable var text: String? {
didSet{
label.text = text
}
}
//Properties
var isSelected = 0
//Initialization
override init(frame: CGRect){
super.init(frame: frame)
addSubviews()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
addSubviews()
}
func addSubviews() {
self.backgroundColor = UIColor.white
let xWidth = bounds.size.width
let xHeight = bounds.size.height
let tap = UITapGestureRecognizer(target: self, action: #selector(xRadioButtonView.radioButtonTextTapped))
button = UIButton(frame: CGRect(x: 1, y: 1, width: xWidth - 2, height: xHeight - 4))
button.backgroundColor = UIColor.white
button.addTarget(self, action: #selector(xRadioButtonView.radioButtonTapped(button:)), for: .touchDown)
addSubview(button)
label = UILabel(frame: CGRect(x: 1, y: 1, width: xWidth - 2, height: xHeight - 2))
label.textColor = UIColor.init(hex: "#D5D5D5")
//label.font = UIFont.init(name: label.font.fontName, size: 25)
//label.font = label.font.withSize(25)
label.font = UIFont.boldSystemFont(ofSize: 25)
label.textAlignment = NSTextAlignment.center
label.isUserInteractionEnabled = true
label.addGestureRecognizer(tap)
addSubview(label)
}
override func layoutSubviews() {
// Set the button's width and height to a square the size of the frame's height.
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
label.text = "xRBV"
}
func radioButtonTapped(button: UIButton) {
if isSelected == 0 {
isSelected = 1
self.backgroundColor = UIColor.init(hex: "#00BFA5")
label.textColor = UIColor.init(hex: "#00BFA5")
} else {
isSelected = 0
self.backgroundColor = UIColor.white
label.textColor = UIColor.init(hex: "#D5D5D5")
}
}
func radioButtonTextTapped(sender: UITapGestureRecognizer){
if isSelected == 0 {
isSelected = 1
self.backgroundColor = UIColor.init(hex: "#00BFA5")
label.textColor = UIColor.init(hex: "#00BFA5")
} else {
isSelected = 0
self.backgroundColor = UIColor.white
label.textColor = UIColor.init(hex: "#D5D5D5")
}
}
}
正如你可以看到PG按鈕要完成其中綠色飾面,但白色按鈕超出屏幕
編輯我的答案。有關如何操作,請參閱其他常量數組。 –
你也可以使用一個元組數組,如果你更喜歡這個元組,可以省去使用枚舉()。我個人認爲我更喜歡平行數組,但是我可以看到爲保持數據的一致性而提出的觀點。 –
太棒了!感謝您的編輯...這種方式比添加不同的限制更好... – xSHERU