i added two custom view classes and the elements of that class are addede to viewcontroller class but i cannot accecssing 1st element but i can access second element
hear my code
1st class
class TextField: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
let view=UIView(frame : CGRectMake(8,100,270,47))
let headerText=UILabel(frame : CGRectMake(0,0,view.bounds.width,16))
headerText.text="label"
headerText.textColor=UIColor.blackColor()
headerText.textAlignment=NSTextAlignment.Left
headerText.font = UIFont.systemFontOfSize(13.0)
headerText.numberOfLines = 0
view.addSubview(headerText)
let textField=UITextField(frame : CGRectMake(0,20,view.bounds.width,28))
textField.borderStyle=UITextBorderStyle.RoundedRect
textField.userInteractionEnabled=true
textField.keyboardType=UIKeyboardType.NamePhonePad
view.addSubview(textField)
self.addSubview(view)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
2nd class
protocol ElementDelegate {
func buttonClick(sender:UIButton)
}
class ButtonClass: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
let button=UIButton(frame: CGRectMake(10,50,270,30))
button.setTitle("Click", forState: UIControlState.Normal)
button.backgroundColor=UIColor.blueColor()
button.userInteractionEnabled=true
button.addTarget(self, action: #selector(button_click(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(button)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func button_click(sender:UIButton){
delegate.buttonClick(sender)
}
}
my viewcontroller class
class ViewController: UIViewController,ElementDelegate {
override func viewDidLoad() {
let screenSize:CGRect=UIScreen.mainScreen().bounds
let date = TextField(frame: CGRectMake(0,10,screenSize.width,screenSize.height))
self.view.addSubview(date)
let element = Button(frame: CGRectMake(0,70,screenSize.width,screenSize.height))
element.delegate = self
self.view.addSubview(element)
}
}
when under running i added first textfield view second i added button view but when i click in textbox i cannot accessing it but button is working fine when i remove button textbox working fine why i cannot accessing both one after another
please help me.....
答案 0 :(得分:0)
let date = TextField(frame: CGRectMake(0,10,screenSize.width,screenSize.height))
...
let element = Button(frame: CGRectMake(0,10,screenSize.width,screenSize.height))
您创建了两个具有完全相同帧(大小和位置)的子视图。您添加的第二个将位于另一个之上,即使其中的按钮和文本字段位于不同的位置,也会接受触摸事件 - 普通UIView
仍会接受触摸事件。
为什么要创建一个视图子类,它只是在另一个位置保存另一个视图?为什么不直接定位按钮和文本字段?