IOS View之間傳值

來源:互聯網
上載者:User

IOS View之間傳值

1、利用NSUserDefaults來傳值,這種方法只限於傳少量資料的情形:

比如你要傳一個float的值,在需要傳的時候用
[[NSUserDefaults standardUserDefaults] setFloat:float forKey::@"float"]
接收值的時候用
[[NSUserDefaults standardUserDefaults] floatForKey:@"float"]

2、NSNotificationCenter來傳值

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
CGRect roundRect = [self rectNeedRefreshFromThisPoint:point];
mLastPoint = CGPointMake(-1, -1);

NSLog(@"%s: point(%f,%f)", __FUNCTION__, point.x, point.y);

[self addToCurrentLineWithPoint:point.x y:point.y];
[self endLine];
[self setNeedsDisplayInRect:roundRect];

NSNumber *pointX = [NSNumber numberWithFloat:point.x];
NSNumber *pointY = [NSNumber numberWithFloat:point.y];
NSDictionary *pointDict = [NSDictionary dictionaryWithObjectsAndKeys:pointX,@"pointX",pointY,@"pointY", nil];
[[NSNotificationCenter defaultCenter]postNotificationName:@"passTouchedEndPointMsg"object:self userInfo:pointDict];

}

在訊息中心的函數:

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(getTouchedPoint:)
name:@"passTouchedEndPointMsg"
object:nil];

- (void) getTouchedPoint:(NSNotification *)noti
{
NSDictionary *pointDict = [noti userInfo];
touchedEndPointX = [[pointDict objectForKey:@"pointX"] floatValue];
touchedEndPointY = [[pointDict objectForKey:@"pointY"] floatValue];
NSLog(@"%f:%f",touchedEndPointX,touchedEndPointY);
}

用訊息來傳參數有下面幾點說法:object指的是寄件者、在poseter端的userInfo裡面可以存放要傳的參數,必須為NSDictionary類型。在center端擷取這個dictionary類型用:[notification userInfo];來擷取

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.