gpt4 book ai didi

ios - 一次只激活一个按钮

转载 作者:搜寻专家 更新时间:2023-11-01 05:48:48 24 4
gpt4 key购买 nike

我正在根据 x 个获取的数据动态创建 x 个按钮。

而且我一次只想激活一个按钮。假设有 3 个按钮,名称分别为 ABC。当用户在 A 处于事件状态时点击 B 时,我想停用 A 并使 B 处于事件状态。

像这样在 jQuery 中很容易实现

$(this).toggleClass('checked').siblings().removeClass('checked');

我如何在 Swift 中执行此操作?

我正在使用以下内容创建按钮:

let frame1 = CGRect(x: 10, y: 6, width: 50, height: 30 )
let button1 = UIButton(frame: frame1)
let attributedTitle = NSAttributedString(string: "\(distinctCategories[i])".uppercaseString, attributes: [NSKernAttributeName: 1.0, NSForegroundColorAttributeName: UIColor.blackColor()])
button1.setAttributedTitle(attributedTitle, forState: .Normal)
button1.titleLabel!.font = UIFont(name: "HelveticaNeue", size: 13.0)
button1.layer.borderWidth = 2.0
button1.layer.borderColor = UIColor.blackColor().CGColor
button1.backgroundColor = UIColor.whiteColor()
button1.addTarget(self, action: "filterByCategory:", forControlEvents: UIControlEvents.TouchUpInside)
self.categoryScrollView.addSubview(button1)

在目标操作中我有:

func filterByCategory(sender:UIButton) {

if sender.backgroundColor != UIColor.blackColor() {

let attributedTitle = NSAttributedString(string: "\((sender.titleLabel?.text)!)".uppercaseString, attributes: [NSKernAttributeName: 1.0, NSForegroundColorAttributeName: UIColor.whiteColor()])
sender.setAttributedTitle(attributedTitle, forState: .Selected)
sender.backgroundColor = UIColor.blackColor()
} else {

let attributedTitle = NSAttributedString(string: "\((sender.titleLabel?.text)!)".uppercaseString, attributes: [NSKernAttributeName: 1.0, NSForegroundColorAttributeName: UIColor.blackColor()])
sender.setAttributedTitle(attributedTitle, forState: .Normal)
sender.backgroundColor = UIColor.whiteColor()
}
}

为了简洁起见,我在这里只显示样式更改。目前我只处理发送者按钮样式的切换,而不是兄弟按钮的切换。

为了反转同级按钮的样式,我尝试将其添加到上面的 if 中。

for button in categoryScrollView.subviews {
if let button = button as? UIButton {
let attributedTitle = NSAttributedString(string: " ", attributes: [NSKernAttributeName: 1.0, NSForegroundColorAttributeName: UIColor.blackColor()])
button.setAttributedTitle(attributedTitle, forState: .Normal)
button.backgroundColor = UIColor.whiteColor()
}
}

但我不确定我这样做是否正确,因为我需要在此目标函数中再次为 setAttributedTitle()

添加所有按钮标题

其他人如何在 Swift 中实现这种按钮切换效果?

最佳答案

我相信您需要的是在 iOS 中实现单选按钮。

这可以使用 UITableView 轻松完成。如果您的需求是在 UIScrollView 中使用 UIButton,那么您可以将这些 UIButton 对象存储在一个数组中并访问它们以实现效果。

假设您有三个 UIButtons A、B、C。在将它们添加到数组之前,为 .Selected 和 .Normal 状态设置它们的属性。您可以将其中之一设置为 Active 作为初始状态。另外,为他们设置独特的标签以供引用

在创建这些按钮时,将它们添加到一个数组中(假设是按钮数组)。然后在函数 filterByCategory(sender:UIButton) 中,执行以下操作

func filterByCategory(sender:UIButton) {

sender.selected = true
for item in array {
if item.tag != sender.tag {
item.selected = false
}
}
}

P.S: 如果您想知道使用 UITableView 执行此操作的方法,可以在评论中对我进行 ping

关于ios - 一次只激活一个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36909650/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com