프로그래밍 방식으로 기본 UIButton을 작성하는 방법 해야합니까? 예를 들어 내 뷰

UIButton프로그래밍 방식 으로 기본을 만들려면 어떻게 해야합니까? 예를 들어 내 뷰 컨트롤러에서 viewDidLoad메소드를 실행할 때 3 UIButton개가 동적으로 생성되고 해당 레이아웃 또는 속성이 설정됩니다.



답변

여기 하나가 있습니다 :

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
           action:@selector(aMethod:)
 forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];


답변

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addMyButton];   // Call add button method on view load
}

- (void)addMyButton{    // Method for creating button, with background image and other properties

    UIButton *playButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
    playButton.frame = CGRectMake(110.0, 360.0, 100.0, 30.0);
    [playButton setTitle:@"Play" forState:UIControlStateNormal];
    playButton.backgroundColor = [UIColor clearColor];
    [playButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal ];
    UIImage *buttonImageNormal = [UIImage imageNamed:@"blueButton.png"];
    UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
    [playButton setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];
    UIImage *buttonImagePressed = [UIImage imageNamed:@"whiteButton.png"];
    UIImage *strechableButtonImagePressed = [buttonImagePressed stretchableImageWithLeftCapWidth:12 topCapHeight:0];
    [playButton setBackgroundImage:strechableButtonImagePressed forState:UIControlStateHighlighted];
    [playButton addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:playButton];
}


답변

목표 -C

UIButton *but= [UIButton buttonWithType:UIButtonTypeRoundedRect];
[but addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
 [but setFrame:CGRectMake(52, 252, 215, 40)];
[but setTitle:@"Login" forState:UIControlStateNormal];
[but setExclusiveTouch:YES];

 // if you like to add backgroundImage else no need
   [but setbackgroundImage:[UIImage imageNamed:@"XXX.png"] forState:UIControlStateNormal];

[self.view addSubview:but];

-(void) buttonClicked:(UIButton*)sender
 {
NSLog(@"you clicked on button %@", sender.tag);
 }

빠른

    let myButton = UIButton() // if you want to set the type use like UIButton(type: .RoundedRect) or UIButton(type: .Custom)
    myButton.setTitle("Hai Touch Me", forState: .Normal)
    myButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
    myButton.frame = CGRectMake(15, 50, 300, 500)
    myButton.addTarget(self, action: "pressedAction:", forControlEvents: .TouchUpInside)

    self.view.addSubview( myButton)


func pressedAction(sender: UIButton!) {
   // do your stuff here 
  NSLog("you clicked on button %@", sender.tag)
}

스위프트 3 이상

  let myButton = UIButton() // if you want to set the type use like UIButton(type: .RoundedRect) or UIButton(type: .Custom)
    myButton.setTitle("Hi, Click me", for: .normal)
    myButton.setTitleColor(UIColor.blue, for: .normal)
    myButton.frame = CGRect(x: 15, y: 50, width: 300, height: 500)

    myButton.addTarget(self, action: #selector(pressedAction(_:)), for: .touchUpInside)
    self.view.addSubview( myButton)



func pressedAction(_ sender: UIButton) {
   // do your stuff here 
  print("you clicked on button \(sender.tag)")
}

스위프트 UI

예를 들어 SwiftUI 개발자 포털 에서 단계별 구현을 얻습니다.

import SwiftUI

struct ContentView : View {
    var body: some View {
        VStack {

            Text("Target Color Black")
             Button(action: {
                 /* handle button action here */ })
            {
         Text("your Button Name")
          .color(.white)
                        .padding(10)
                        .background(Color.blue)
                        .cornerRadius(5)
                        .shadow(radius: 5)
                        .clipShape(RoundedRectangle(cornerRadius: 5))
     }


        }
    }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif


답변

프로그래밍 방식으로 컨트롤러의보기에 버튼을 추가하려면 다음을 사용하십시오.

-(void)viewDidLoad
{
   UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
   btn.frame = CGRectMake(0, 0, 100, 50);
   [btn setTitle:@"Hello, world!" forState:UIControlStateNormal];
   [self.view addSubview:btn];
}

이 중 세 가지를 추가하려면 헹구고 반복하십시오.


답변

여기서 UIButton을 동적으로 만들 수 있습니다.

//For button image
UIImage *closebtnimg = [UIImage imageNamed:@"close_btn.png"];
//Custom type button
btnclose = [[UIButton buttonWithType:UIButtonTypeCustom]retain];
//Set frame of button means position
btnclose.frame = CGRectMake(103, 257, 94, 32);
//Button with 0 border so it's shape like image shape
[btnclose.layer setBorderWidth:0];
//Set title of button
[btnclose setTitle:@"CLOSE" forState:UIControlStateNormal];
[btnclose addTarget:self action:@selector(methodname:) forControlEvents:UIControlEventTouchUpInside];
//Font size of title
btnclose.titleLabel.font = [UIFont boldSystemFontOfSize:14];
//Set image of button
[btnclose setBackgroundImage:closebtnimg forState:UIControlStateNormal];


답변

어서, 2014 년이야! 왜 안되는 코드 블록 평가 할당 으로, 아직 사용되는 경향이 보여 그것은의 미래!

UIButton* button = ({
    //initialize button with frame
    UIButton* button = [[UIButton alloc] initWithFrame:({
        CGRect frame = CGRectMake(10.0, 10.0, 200.0, 75.0);
        frame;
    })];
    //set button background color
    [button setBackgroundColor:({
        UIColor* color = [UIColor colorWithRed:1.0 green:1.0 blue:0.0 alpha:1.0];
        color;
    })];
    //set button title for state
    [button setTitle:({
        NSString* string = [NSString stringWithFormat:@"title words"];
        string;
    }) forState:({
        UIControlState state = UIControlStateNormal;
        state;
    })];
    //set selector
    [button addTarget:self action:({
        SEL select = @selector(method:);
        select;
    }) forControlEvents:({
        UIControlEvents event = UIControlEventTouchUpInside;
        event;
    })];
    //return button
    button;
});
[self.view addSubview:button];

우와!

우와!

또는 다음과 같이 정확한 결과를 얻을 수 있습니다.

UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(10.0, 10.0, 200.0, 75.0)];
[button setBackgroundColor:[UIColor colorWithRed:1.0 green:1.0 blue:0.0 alpha:1.0]];
[button setTitle:@"title words" forState:UIControlStateNormal];
[button addTarget:self action:@selector(method:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];


답변

'action:@selector(aMethod:)' 다음과 같은 방법을 작성하십시오.

- (void)aMethod:(UIButton*)button
   {
         NSLog(@"Button  clicked.");
  }

그것은 나를 위해 작동합니다. 감사. 캔사스