我可以更新UIButton中的标签而无需重新绘制按钮吗?

时间:2017-06-09 07:45:42

标签: objective-c uiview uibutton delegates nstimer

我希望时钟读数在UIButton每秒一次显示为标签。但即使我从superView中移除它,新的UIButton会覆盖旧的PlayViewController,例如enter image description here ......几分钟后我的iPhone看起来很严重: - )

NSTimer我的 - (void)startClock { clockCount = 0; // start on 1st clock pulse totalMinutes = 0; // appears on clockButton totalSeconds = 0; // appears on clockButton timer = [NSTimer scheduledTimerWithTimeInterval:STATES_ConcertClock target:self selector:@selector(nextClock) userInfo:nil repeats:YES]; } - (void)nextClock { self.lastEventChangeTime = [NSDate date]; clockCount++; [self masterClockReadout]; } 方法看起来像这样

    - (void)masterClockReadout                              {
        totalMinutes       = clockCount / 60;
        totalSeconds       = clockCount % 60;
        clockString        = [NSString stringWithFormat:@"%02d:%02d", totalMinutes, totalSeconds];

        [self.seconds removeFromSuperview];
        EscButton *seconds = [[EscButton alloc] loadEscButton:(NSString *)clockString];
        [self.view addSubview:seconds];
    }

这是我的时钟读数方法

UIView

我还设置了removeFromSuperview属性,因此 @property (nonatomic, retain) UIView* seconds; 知道要删除的内容。

UIButton

我的问题是:我可以在不重新绘制按钮的情况下更新delegate标签吗?这是一个可以通过使用delegates

解决的问题

到目前为止,我使用UIButton的体验是将信息从ViewController发送到delegate (例如下面),但到目前为止,我还没有使用 #import <UIKit/UIKit.h> @protocol EscButtonDelegate <NSObject> -(void)fromEscButton:(UIButton*)button; @end @interface EscButton : UIView { } - (id)loadEscButton:(NSString *)text; @property (assign) id<EscButtonDelegate> delegate; @end 。我发现了一个例子,我可以应用在相反方向发送消息的地方。因此,如果使用 #import "EscButton.h" @implementation EscButton - (id)loadEscButton:(NSString *)text { CGFloat sideOffset = screenWidth - ESC_BUTTON_Width - MARGIN_Side; CGFloat topOffset = statusBarHeight + MARGIN_Top; UIButton *escButton = [UIButton buttonWithType:UIButtonTypeCustom]; escButton.frame = CGRectMake(sideOffset, topOffset, ESC_BUTTON_Width, ESC_BUTTON_Height); // etc … [escButton addTarget:self.delegate action:@selector(fromEscButton:) forControlEvents:UIControlEventTouchUpInside]; [escButton setTitle:text forState:UIControlStateNormal]; // etc … return escButton; } @end 是推荐的方法,请指点一些可能有助于我解决此问题的代码。谢谢

EscButton.h

SyntaxError

EscButton.m

...

1 个答案:

答案 0 :(得分:1)

无需不断添加和删除按钮。你可以保持同一个。更改以下代码:

@property (nonatomic, retain) UIView* seconds;

为:

@property (nonatomic, retain) UIButton *secondsB;

同样改变:

[self.seconds removeFromSuperview];
EscButton *seconds = [[EscButton alloc] loadEscButton:(NSString *)clockString];
[self.view addSubview:seconds];

为:

if (!self.secondsB) {

    self.secondsB = [[EscButton alloc] loadEscButton:(NSString *)clockString];
    [self.view addSubview:_secondsB]; // previously addSubview:seconds]; 
}

[self.secondsB setTitle:clockString forState:UIControlStateNormal];