Как мне создать базовую UIButton программно?

Вы можете проверить, как показано ниже,

from django.test import TransactionTestCase, Client

class UserHistoryTest(TransactionTestCase):
    self.user = User.objects.create(username='admin', password='pass@123', email='admin@admin.com')
    self.client = Client() # May be you have missed this line

    def test_history(self):
        self.client.login(username=self.user.username, password='pass@123')
        # get_history function having login_required decorator
        response = self.client.post(reverse('get_history'), {'user_id': self.user.id})
        self.assertEqual(response.status_code, 200)

Этот тестовый пример работал для меня.

538
задан Leo Dabus 6 November 2017 в 05:00
поделиться

11 ответов

Вот один из них:

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];
1172
ответ дан Fahim Parkar 6 November 2017 в 05:00
поделиться

Версия Swift3 должна быть

let myButton:UIButton = {
            let myButton = UIButton() // if you want to set the type use like UIButton(type: .RoundedRect) or UIButton(type: .Custom)
            myButton.setTitle("Hai Touch Me", for: .normal)
            myButton.setTitleColor(UIColor.blue, for: .normal)
            myButton.frame = CGRect(x: 20, y: 20, width: 100, height: 40)

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

            return myButton

        }()
0
ответ дан Jacky 6 November 2017 в 05:00
поделиться
UIButton *buttonName = [UIButton
buttonWithType:UIButtonTypeRoundedRect];
[buttonName addTarget:self 
    action:@selector(aMethod:)forControlEvents:UIControlEventTouchDown];
[buttonName setTitle:@"Show View" forState:UIControlStateNormal];
.frame = CGRectMake(80.0, 210.0, 160.0, 40.0); [view
addSubview:buttonName];
0
ответ дан byJeevan 6 November 2017 в 05:00
поделиться
UIButton *addProject = [UIButton buttonWithType: UIButtonTypeRoundedRect];
addProject.frame = CGRectMake(210, 285, 100, 18);
[addProject setTitle:@"Show View" forState:UIControlStateNormal];
[addProject addTarget:self action:@selector(addProjectPressed:) forControlEvents:UIControlEventTouchUpInside];
[_scrollView addSubview:addProject];
-1
ответ дан Ved Rauniyar 6 November 2017 в 05:00
поделиться

Objective-C

// Create the Button with RoundedRect type
UIButton *mybutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// instend of "Click Me" you can write your own message/Label
[mybutton setTitle:@"Click Me" forState:UIControlStateNormal];
// create the Rectangle Frame with specified size
mybutton.frame = CGRectMake(10, 10, 300, 140); // x,y,width,height    [self.view addSubview:mybutton];// add button to your view.

Swift

let button   = UIButton(type: UIButtonType.System) as UIButton
button.frame = CGRectMake(100, 100, 100, 50)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Test Button", forState: UIControlState.Normal)
self.view.addSubview(button)
14
ответ дан Himanshu padia 6 November 2017 в 05:00
поделиться
-(UIButton *)addButton:(NSString *)title :(CGRect)frame : (SEL)selector :(UIImage *)image :(int)tag{

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = frame;
[btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:title forState:UIControlStateNormal];
[btn setImage:image forState:UIControlStateNormal];
btn.backgroundColor = [UIColor clearColor];
btn.tag = tag;

return btn;

}

и вы можете добавить его в представление:

[self.view addSubview:[self addButton:nil :self.view.frame :@selector(btnAction:) :[UIImage imageNamed:@"img.png"] :1]];
4
ответ дан Mutawe 6 November 2017 в 05:00
поделиться

Чтобы добавить кнопку программно в вид вашего контроллера, используйте следующее:

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

Чтобы добавить три из них, промойте и повторите.

30
ответ дан Jason 6 November 2017 в 05:00
поделиться

'action:@selector(aMethod:)' напишите метод так:

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

Это работает для меня. Благодарю. KS.

20
ответ дан Shadwell 6 November 2017 в 05:00
поделиться

Начиная с Swift 3, несколько изменений были внесены в синтаксис.

Вот как вы можете создать базовую кнопку с Swift 3:

    let button = UIButton(type: UIButtonType.system) as UIButton
    button.frame = CGRect(x: 100, y: 100, width: 100, height: 50)
    button.backgroundColor = UIColor.green
    button.setTitle("Example Button", for: UIControlState.normal)
    self.view.addSubview(button)

Вот изменения, которые были сделаны со времен предыдущих версий Swift :

let button = UIButton(type: UIButtonType.System) as UIButton

// system no longer capitalised

button.frame = CGRectMake(100, 100, 100, 50)

// CGRectMake has been removed as of Swift 3

button.backgroundColor = UIColor.greenColor()

// greenColor replaced with green

button.setTitle("Example Button", forState: UIControlState.Normal)

// normal is no longer capitalised

self.view.addSubview(button)
1
ответ дан GJZ 6 November 2017 в 05:00
поделиться

Вы можете просто поместить экземпляр создателя в цикл и динамически добавлять имена из массива, если хотите.

6
ответ дан 22 November 2019 в 22:23
поделиться
- (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];  
}
93
ответ дан 22 November 2019 в 22:23
поделиться
Другие вопросы по тегам:

Похожие вопросы: