改變UIButton上標題位置、文字顏色、背景色等
阿新 • • 發佈:2019-02-05
示例程式碼+註釋
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, 200, 100)]; //新增點選事件 [button addTarget:self action:@selector(pushToSecond) forControlEvents:UIControlEventTouchUpInside]; //整個按鈕的背景色(無背景圖片時有效果) button.backgroundColor = [UIColor greenColor]; //新增背景圖片 [button setBackgroundImage:[UIImage imageNamed:@"01.png"] forState:UIControlStateNormal]; //按鈕標題 [button setTitle:@"Hello World!" forState:UIControlStateNormal]; //button上子控制元件的水平對齊方式 button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; //button上子控制元件的垂直對齊方式 button.contentVerticalAlignment = UIControlContentVerticalAlignmentTop; //內容容器的偏移,讓文字向右偏移20畫素 button.contentEdgeInsets = UIEdgeInsetsMake(0,20, 0, 0); //設定標題的背景顏色 button.titleLabel.backgroundColor = [UIColor purpleColor]; //標題顏色 [button setTitleColor:[UIColor yellowColor]forState:UIControlStateNormal]; button.imageView.contentMode = UIViewContentModeScaleAspectFit; [self.view addSubview:button]; [button release];