UILabel 中显示的整数减一
我有一个 UILabel,当按下按钮时,它的值会加一——基本上它会向上计数。有人可以帮我减号按钮吗?这样,如果用户不小心按了添加按钮超过了他们需要的次数,他们就可以减少他们的错误。我已经尝试过,但标签的文本现在设置为-1。我希望它每次按下时都减一:
- (IBAction)subtractButton:(id)sender {
static int integerSaved;
integerSaved = integer;
integerSaved -= 1;
[label2 setText:[NSString stringWithFormat:@"%i", integerSaved]];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
Try this:
此代码假定您没有使用 Interface Builder,并且您手动将“subtract”链接到 UIButton。如果您使用 Interface Builder,请尝试此代码。
我还没有测试过这个,但我认为它应该有效。祝你好运!
This code assumes that you are not using Interface Builder, and that you are manually linking "subtract" to the UIButton. If you are using Interface Builder, try this code.
I have not tested this but I think it should work. Good luck!
使用
UIView
实例的值进行算术运算不是 MVC-方式。您确实应该将数据模型与视图分开。在某个类中公开
int
、NSInteger
或NSNumber
属性,该类专用于保存应用程序的数据值。当给定按钮发生触摸事件时,增加数据属性并触发一个通知,根据属性中的内容更新视图。或者向该属性添加观察者。当属性值发生变化时,观察者会更新视图。
遵循 MVC 模式将是一种更像“Apple”或“iOS”的做事方式,而不是获取 UIView 的值,将其转换为整数,然后将其转换回来到一个字符串。
Using the value of the
UIView
instance to do arithmetic is not the MVC-way. You should really be separating your data model from your view.Expose an
int
,NSInteger
orNSNumber
property in a class somewhere, where that class is dedicated to holding data values for your app.When a touch event comes in for a given button, increment the data property and fire a notification that updates the view based on what's in the property. Or add an observer to the property. The observer then updates the view when the property value changes.
Following the MVC pattern would be a more "Apple"-ish or "iOS"-ish way of doing things, than getting the
UIView
's value, converting it to an integer, and then converting it back to a string.