Swift use
picker to show a list of item for user choose, it look simple.
We want to make
it like Android spinner.
Declare a
button, when clicked, it show a list of year, if user choose a row, set result
to label.
var la: UILabel!
var bu:UIButton!
Declare an
array.
let data=["2000","2001","2002","2003","2004","2005","2006","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016","2017","2018","2019","2020","2021","2022","2023"]
Set position to
button, label.
bu = UIButton(frame: CGRect(x:80, y: 530, width: 100, height: 32))
setbu(bu,"Choose
year")
la = UILabel(frame: CGRect(x: 80, y: 500, width: 100, height: 25))
view.addSubview(bu)
view.addSubview(la)
This is
function to make button.
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
}
This is
function to make list.
func spinner(sender: UIButton){
let alert = UIAlertController(title: "Choose year", message: "", preferredStyle: .Alert)
for i in 0..<data.count {
alert.addAction(UIAlertAction(title: String(data[i]), style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction) ->Voidin
let a=NSMutableAttributedString(string: self.data[i], attributes: [NSForegroundColorAttributeName: UIColor.blueColor(), NSFontAttributeName: UIFont(name: "Arial", size: 15.0)!])
self.bu.setAttributedTitle(a, forState: .Normal)
let h=String(self.data[i])
self.la.text=h
self.la.textColor = UIColor.blueColor()
}))
}
alert.addAction(UIAlertAction(title: "Cancel",
style: UIAlertActionStyle.Cancel,
handler:nil))
self.presentViewController(alert, animated: true, completion: nil)
}
Set function to
button in viewDidLoad
bu.addTarget(self, action: #selector(ViewController.spinner(_:)), forControlEvents: UIControlEvents.TouchUpInside)
Run to see
result.
No comments:
Post a Comment