如何在XCode中按下某个按钮时禁用所有按钮?
我该如何制作,以便当我按下XCode中的一个按钮时,剩下的按钮(包括被按下的按钮)变为禁用状态?当然,我仍然希望通过按下按钮来执行该功能。我只是不希望用户能够多次按下任何按钮,也不希望他们在按下第一个按钮后再按下另一个按钮。下面是我为我的两个按钮IBActions在这种情况下:如何在XCode中按下某个按钮时禁用所有按钮?
@IBAction func addVote1(sender: AnyObject) {
var query = PFQuery(className: "VoteCount")
query.getObjectInBackgroundWithId("BiEM17uUYT") {
(voteCount1: PFObject!, error: NSError!) ->Void in
if error != nil {
NSLog("%@", error)
} else {
voteCount1.incrementKey("votes")
voteCount1.saveInBackgroundWithTarget(nil, selector: nil)
}
let votes = voteCount1["votes"] as Int
let votes2 = voteCount1["votes2"] as Int
self.pollResults1.text = "\(votes) votes \(votes2) votes"
}
}
@IBAction func addVote2(sender: AnyObject) {
var query = PFQuery(className: "VoteCount")
query.getObjectInBackgroundWithId("BiEM17uUYT") {
(voteCount1: PFObject!, error: NSError!) -> Void in
if error != nil {
NSLog("%@", error)
} else {
voteCount1.incrementKey("votes2")
voteCount1.saveInBackgroundWithTarget(nil, selector: nil)
}
let votes = voteCount1["votes"] as Int
let votes2 = voteCount1["votes2"] as Int
self.pollResults2.text = "\(votes) votes \(votes2) votes"
}
}
}
的按钮设置@IBOutlet
属性,如果你有没有准备好,然后添加一个lazy var
阵列的按钮。在按钮处理程序中,将每个按钮的enabled
属性设置为false。
class ViewController {
@IBOutlet var button1: UIButton!
@IBOutlet var button2: UIButton!
lazy var buttons: [UIButton] = [self.button1, self.button2]
// ...
@IBAction func addVote1(sender: AnyObject) {
for button in self.buttons {
button.enabled = false
}
// ...
}
}
做一两件事,所有的按钮提供独特标签。之后,创建它创建按钮的方法和使用按钮标记
func disableButton()
{
for tagvalue in 101...102
{
var btnTemp = self.view.viewWithTag(tagvalue) as UIButton;
btnTemp.enabled = false;
}
}
添加上述方法在您的按钮,禁用它们如下面的代码所示
@IBAction func addVote1(sender: AnyObject)
{
//Your code
disableButton()
}
@IBAction func addVote2(sender: AnyObject)
{
//Your code
disableButton()
}
最简单的方法是添加一个UIView与顶部是UIColor.clearColor()的背景颜色。它是不可见的,捕获所有的水龙头。
class ViewController {
private var uiBlocker = UIView()
override func viewDidLoad() {
uiBlocker.backgroundColor = UIColor.clearColor()
}
@IBAction func buttonAction() {
view.addSubView(uiBlocker)
[stuff you want to do]
uiBlocker.removeFromSuperView()
}
}
let subviews : NSArray = headerView.subviews as NSArray
for button in subviews {
if let button = button as? UIButton {
//let btn = button as! UIButton
button.isSelected = false
}
}
sender.isSelected = true
您可以通过UIView的所有子视图循环,并发现如果是一个UIButton,如果是你可以禁用按钮。
func disableButtons() {
for views in view.subviews {
if let button = views as? UIButton {
button.enabled = false
}
}
}
请花一分钟来解释你的代码。当你解释你的代码时,你可能会收到一个加号。 – 2016-11-17 14:28:43
编辑答案,tks – 2016-11-18 16:47:20
我已经为两个按钮设置了IBOutlet属性。我是否需要将惰性var添加到现有的IBOutlet属性中,还是需要完全创建新的IBOutlet属性? – ansariha 2014-11-06 04:16:41
添加了一些示例代码供参考 - 您需要将其调整为适合您的课程。 – 2014-11-06 04:17:30