programing

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

instargram 2023. 6. 1. 22:14
반응형

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

x,y 위치를 조정할 수 있습니까?titleLabel상당한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)

스위프트 5

button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .top
button.titleEdgeInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 0.0, right: 0.0)

시각적으로 가장 쉬운 방법은 속성 검사기**(xib/storyboard를 편집할 때 표시됨)를 사용하여 "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
    }

}

이것은 xib에서 할 수 있습니다.단추를 선택하고 "Size Inspector" 탭으로 이동한 후 세트를 설정합니다.

여기에 이미지 설명 입력

언급URL : https://stackoverflow.com/questions/2808078/is-it-possible-to-adjust-x-y-position-for-titlelabel-of-uibutton

반응형