We want to use
a textField inside a Dialog to get user input data.
Declare button,
label
var la: UILabel!
var bu:UIButton!
Set position,
name button as “Enter name”.
bu = UIButton(frame: CGRect(x:80, y: 530, width: 100, height: 32))
setbu(bu,"Enter
name")
Set label text
to orange color.
la = UILabel(frame: CGRect(x: 80, y: 500, width: 100, height: 25))
la.textColor = UIColor.orangeColor()
view.addSubview(bu)
view.addSubview(la)
Declare a
function name gettext.
func gettext(sender: UIButton){
let alert = UIAlertController(title: "Enter name", message: "", preferredStyle: .Alert)
alert.addTextFieldWithConfigurationHandler({(te: UITextField!) in
te.placeholder = "Name"
})
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction) ->Voidin
let ten = alert.textFields
let ten2 = ten! as [UITextField]
let n = ten2[0].text
let s = n!.characters.count
if s <1 {
self.toast("You enter nothing!")
self.presentViewController(alert, animated: true, completion: nil)
}
else{
self.la.text=n!
}
}))
alert.addAction(UIAlertAction(title: "Cancel",
style: UIAlertActionStyle.Cancel,
handler:nil))
self.presentViewController(alert, animated: true, completion: nil)
}
We check if
user type nothing, so toast, if t has text, set to label.
Set function to
button in viewDidLoad.
bu.addTarget(self, action: #selector(ViewController.nhapchu(_:)), forControlEvents: UIControlEvents.TouchUpInside)
Run to see
result.
Function use to
create button like this.
func setbu(bun:UIButton,_ t: String){
let a=NSMutableAttributedString(string: t, attributes: [NSForegroundColorAttributeName: UIColor.blueColor(), NSFontAttributeName: UIFont(name: "Arial", size: 15.0)!])
bun.setAttributedTitle(a, forState: .Normal)
bun.backgroundColor = hex("#e6e6fa")
bun.layer.cornerRadius = 16
bun.layer.borderColor = hex("#6699cc").CGColor
bun.layer.borderWidth = 1
}
Func toast can
see here.
No comments:
Post a Comment