Swift 代码生成label和button

15. March 2016 Swift 1

self.btn.setTitle(“lijian”, forState: UIControlState.Normal)//设置按钮

let width = UIScreen.mainScreen().bounds.width;

let height = UIScreen.mainScreen().bounds.height; //获取屏幕尺度

var  label = UILabel(frame: CGRectMake(10, 20, 300, 100))

label.text = “this is a wondowful book”;

label.textColor=UIColor.redColor();

label.textAlignment = NSTextAlignment.Right//文字右对齐

label.shadowColor = UIColor.grayColor()//设置阴影颜色

label.shadowOffset = CGSizeMake(-5, 5)//设置阴影偏移(左和下)

label.font = UIFont(name: “楷体”, size: 20)//设置字体和大小

label.lineBreakMode = NSLineBreakMode.ByTruncatingHead //隐藏头部并显示省略号

label.lineBreakMode = NSLineBreakMode.ByTruncatingTail //隐藏尾部并显示省略号

label.lineBreakMode = NSLineBreakMode.ByTruncatingMiddle //隐藏中间并显示省略号

label.lineBreakMode = NSLineBreakMode.ByClipping //截取多余部分,不现实省略号

label.adjustsFontSizeToFitWidth = true // 通过缩小文字把一行全部显示出来

label.numberOfLines = 2 //设置显示的行

self.view.addSubview(label)  //生成label标签

——————————————————————————————————————

let button = UIButton(type: UIButtonType.ContactAdd)//创建带加号的按钮,触摸高亮

let button1 = UIButton(type: UIButtonType.DetailDisclosure) //“!”图标按钮,触摸高亮

let button2 = UIButton(type: UIButtonType.System)//不带图标,默认文字颜色为蓝色,触摸高亮

var button3 = UIButton(type: UIButtonType.Custom) //定制按钮,不带图标,默认颜色为白色,无触摸高亮

button3 = UIButton(frame: CGRectMake(10, 150, 100, 30)) //Custom类型按钮简化创建代码

button.frame = CGRectMake(10, 150, 100, 30)//按钮的大小和位置

button.setTitle(“按钮”, forState: UIControlState.Normal)//文字默认为蓝色

button.setTitle(“触摸状态”, forState: UIControlState.Highlighted)//触摸高亮

button.setTitle(“禁用状态”, forState: UIControlState.Disabled)//按钮禁用状态

button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Highlighted);//设置不同状态的颜色

button.backgroundColor = UIColor.blackColor();//设置背景颜色

button.setImage(UIImage(named: “icon”), forState: UIControlState.Normal)//设置背景图片

button.adjustsImageWhenHighlighted = false //按钮触摸时候,图标不变暗

button.adjustsImageWhenDisabled = false //禁用状态下图标不会变暗

button.setBackgroundImage(UIImage(named: “icon”), forState: UIControlState.Normal)//设置按钮背景图片

button.addTarget(self, action: Selector(“lijian:”), forControlEvents: UIControlEvents.TouchUpInside)

//第一个参数传递对象,第二个action传递对象方法,第三个参数传递事件类型。当在tapped中获得按钮对象,需要在方法名后面加冒号

self.view.addSubview(button)

}

func lijian(button:UIButton){

print(“被调用了”)

print(button.titleForState(UIControlState.Normal))

}


Leave a Reply

Your email address will not be published. Required fields are marked *