Programing

UIButton의 titleLabel에 대해 x, y 위치를 조정할 수 있습니까?

lottogame 2020. 7. 20. 21:08
반응형

UIButton의 titleLabel에 대해 x, y 위치를 조정할 수 있습니까?


그것을위한 X, Y 위치를 조정할 수있다 titleLabel(A)의를 UIButton?

내 코드는 다음과 같습니다.

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    [btn setFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
    [btn setTitle:[NSString stringWithFormat:@"Button %d", i+1] forState:UIControlStateNormal];     
    [btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    btn.titleLabel.frame = ???

//make the buttons content appear in the top-left
[button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[button setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];

//move text 10 pixels down and right
[button setTitleEdgeInsets:UIEdgeInsetsMake(10.0f, 10.0f, 0.0f, 0.0f)];

그리고 스위프트에서

//make the buttons content appear in the top-left
button.contentHorizontalAlignment = .Left
button.contentVerticalAlignment = .Top

//move text 10 pixels down and right
button.titleEdgeInsets = UIEdgeInsetsMake(10.0, 10.0, 0.0, 0.0)

시각적으로 가장 쉬운 방법 은 속성 관리자 ** (xib / 스토리 보드를 편집 할 때 나타남)를 사용하고 " edge "속성을 제목으로 설정하고 삽입 된 부분을 조정 한 다음 "edge"속성을 이미지로 설정하고 그에 따라 조정하는 것입니다. . 유지 관리가 쉽고 시각적이 높기 때문에 일반적으로 코딩하는 것보다 낫습니다.

속성 관리자 설정


UIButton에서 파생하여 다음 방법을 구현하십시오.

- (CGRect)titleRectForContentRect:(CGRect)contentRect;

편집하다:

@interface PositionTitleButton : UIButton
@property (nonatomic) CGPoint titleOrigin;
@end

@implementation PositionTextButton
- (CGRect)titleRectForContentRect:(CGRect)contentRect {
  contentRect.origin = titleOrigin;
  return contentRect;
}
@end

내 프로젝트에는이 확장 유틸리티가 있습니다.

extension UIButton {

    func moveTitle(horizontal hOffset: CGFloat, vertical vOffset: CGFloat) {
        self.titleEdgeInsets.left += hOffset
        self.titleEdgeInsets.top += vOffset
    }

}

참고 URL : https://stackoverflow.com/questions/2808078/is-it-possible-to-adjust-xy-position-for-titlelabel-of-uibutton

반응형