2010-06-25 2 views
1

Objective-C를 사용하여 첫 번째 앱 중 하나를 만들었습니다. 멍청한 놈이기 때문에 내가하고 싶은 많은 것들이 있지만 Objective-C에서 그것을 적용하는 방법을 모른다. 아래에서 (내가 처음부터 만들었던) 방법을 살펴보고 더 잘 만들 수있는 방법을 알려주십시오. 분명히 나는 ​​2 개의 UILabels에 걸쳐 코드를 복제했지만 코드를 복제하는 것이 싫어서 단순화하고 싶지만 가장 좋은 방법은 무엇인지 알지 못합니다. 난 그냥 나에게 더 나은 목표 - C에서 물건을 할 수있는 올바른 방법을 이해하는 데 도움이됩니다 제안이 필요Objective-C를 처음 사용하는 닷넷 개발자. 비평과 제안이 필요합니다.

timeText 및 dateText 당신의 도움에 대한 UILabel의

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    if (isRearranging) 
    { 
     NSLog(@"touchesMoved"); 
     NSLog(@"touches=%@,event=%@",touches,event); 
     //TOUCH INFO 
     UITouch *touch = [[touches allObjects] objectAtIndex:0]; 
     CGPoint currentLocation = [touch locationInView:touch.view]; 
     CGPoint previousLocation = [touch previousLocationInView:touch.view]; 
     //FRAME INFO 
     float timeHalfWidth = timeText.frame.size.width/2; 
     float timeHalfHeight = timeText.frame.size.height/2; 
     CGRect timeTextRect = CGRectMake(timeText.center.x - (timeHalfWidth), timeText.cener.y - (timeHalfHeight), timeText.frame.size.width, timeText.frame.size.height); 
     float dateHalfWidth = dateText.frame.size.width/2; 
     float dateHalfHeight = dateText.frame.size.height/2; 
     CGRect dateTextRect = CGRectMake(dateText.center.x - (dateHalfWidth), dateText.center.y - (dateHalfHeight), dateText.frame.size.width, dateText.frame.size.height); 
     //IF TIME TEXT 
     if(CGRectContainsPoint(timeTextRect,previousLocation)) 
     { 
      CGPoint item = timeText.center; 
      CGPoint diff; 
      diff.x = previousLocation.x - item.x; 
      diff.y = previousLocation.y - item.y; 
      CGPoint newLoc; 
      newLoc.x = currentLocation.x - diff.x; 
      newLoc.y = currentLocation.y - diff.y; 
      if (newLoc.x<timeHalfWidth) 
       newLoc.x = timeHalfWidth; 
      if (newLoc.y<timeHalfHeight) 
       newLoc.y = timeHalfHeight; 
      [timeText setCenter:(newLoc)]; 
     } 
     //IF DATE TEXT 
     if(CGRectContainsPoint(dateTextRect,previousLocation)) 
     { 
      CGPoint item = dateText.center; 
      CGPoint diff; 
      diff.x = previousLocation.x - item.x; 
      diff.y = previousLocation.y - item.y; 
      CGPoint newLoc; 
      newLoc.x = currentLocation.x - diff.x; 
      newLoc.y = currentLocation.y - diff.y; 
      if (newLoc.x<dateHalfWidth) 
       newLoc.x = dateHalfWidth; 
      if (newLoc.y<dateHalfHeight) 
       newLoc.y = dateHalfHeight; 
      [dateText setCenter:(newLoc)];  
     } 
    } 
    touchMoved = YES; 
} 

정말 고마워요 유형입니다

!

+0

게시물을 편집하고 코드를 모두 강조 표시 한 다음 텍스트 편집기에서 코드 버튼을 클릭하십시오. –

+1

1 단계, 게시 할 때 코드 형식을 지정하십시오. –

답변

4

작업하고있는 언어와 관계없이 첫 번째 단계는 DRY을 따라야합니다. 대부분의 코드는 두 레이블에서 모두 동일합니다.
그런 다음 이미 SDK의 히트 테스트 기능이 있습니다 (예 : -hitTest:withEvent: 또는 -pointInside:withEvent:는 :

NSArray *labels = [NSArray arrayWithObjects:timeText, dateText, nil]; 
for (UILabel *label in labels) { 
    if ([label pointInside:previousLocation withEvent:nil]) { 
     [self relocateLabel:label]; 
     break; 
    } 
} 
+0

DRY는 내가 코드를 중복한다고 특별히 언급 한 이유입니다. 누군가가 내 복제본을 올바른 방식으로 다시 쓰는 것을보고 싶었습니다. 당신은 내가 뭘 찾았는지 정확하게 알려 줬어. 배열에서 혼합 유형을 사용하려면 어떻게해야합니까? 즉 UILabel과 UIImageView가 있습니다. 유형을 비교하거나 제네릭을 사용하는 방법이 있습니까? 이것은 (* NSObject의 오브젝트 OBJ)에 { 경우 (label.type == UILabel의) [자기 relocateLabel : OBJ]에 대하여 빈 추측/예 ; else if (label.type == UIImageView) [self relocateImage : obj]; } – Ricky

+0

@Ricky : Objective-C 메시지 전달은 동적이며 두 가지 예 모두'UIView'에서 파생됩니다. - UIView에서 메서드를 사용하는 한'for (UIView * 뷰) 뷰 '와'-relocateView : (UIView *) 뷰'. –

1

나는 코멘트에 아스 커로 인한 추가 질문에 대답합니다. 제품 견적 :

해당 배열에서 혼합 유형을 사용하려면 어떻게해야합니까? 즉 UILabel과 UIImageView가 있습니다. 유형을 비교하거나 제네릭을 사용하는 방법이 있습니까? 이것은 (NSObject * obj in objects) {if (label.type == UILabel) [self relocateLabel : obj]에 대한 나쁜 추측/예입니다. else if (label.type == UIImageView) [self relocateImage : obj]; }

Georg Fritzsche가 응답 한대로 Objective-C 메시지는 동적입니다. 런타임에 해당 메시지를 지원하는 경우 개체가 쿼리되며 해당하는 경우 메시지와 연결된 메서드가 실행됩니다. 메소드/메시지 이름을 "선택자"라고합니다.

명시 적으로 개체의 클래스를 알아 내고 싶다면 그렇게 할 수도 있습니다.

if([view isKindOfClass:[UILabel class]]) 
{ 
    // your code here 
} 

방금 ​​대상 개체가 선택에 응답하는지 알아 내야 할 경우 (즉, 메소드를 구현) :

if([view respondsToSelector:@selector(relocateView:)]) 
{ 
    // your code here 
} 

선택기, 인수 자체를 생략 남겨 메소드 이름에서 파생 된 콜론은 그대로두고 모든 것을 가깝게 추가합니다. 예를 들어, 메시지 전송 (즉, 메소드 호출)이있는 경우 : [thing moveTowardsObject:door movementType:XYZ_CRAWL], 선택자는 moveTowardsObject:movementType:이고 @selector(moveTowardsObject:movementType:)을 사용합니다.

게오르그 (Georg)가 게시 한 루프에서 일반적으로 대상 개체가 선택기에 응답하는지 확인하는 것이 좋습니다. 그렇지 않으면 예외가 발생하고 Objective-C 코드는 일반 코드의 일부로 예외를 거의 잡지 않으므로 (파이썬 개발자가하는 것과는 반대되는) 흐름.

관련 문제